W3C

HTML 5.1

W3C Recommendation,

4.7. 삽입(embedded) 콘텐트

4.7.1. 소개

이 섹션은 비규범적입니다.

단일 이미지 리소스가 존재하는 경우, HTML에 이미지를 삽입하기 위해 img 요소(element)와 그것의 srcalt 속성(attribute)들을 사용합니다.

<h2>From today’s featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

하지만, 작성자들이 유저 에이전트가 선택할 수 있는 여러 이미지 리소스들을 사용하기를 원할 수 있는 여러 상황들이 있습니다:

위 상황들은 상호 배타적이지 않습니다. 예를 들어, 다른 기기 픽셀 비율에 대한 다른 리소스들을 art direction에 대한 다른 리소스들과 결합하는 것은 합리적입니다.

스크립팅을 사용하여 이 문제들을 해결하는 것이 가능한 반면, 그렇게 하는 것은 다른 문제들을 도입시킵니다:

이를 염두해 두고, 이 명세는 선언적 방법으로 위 문제를 해결하는 많은 기능들을 소개합니다.

이미지의 렌더링 된 크기가 고정 된 경우 기기 픽셀 비율기반 선택

img 요소(element)의 srcsrcset 속성(attribute)들이 크기가 다양한 여러 이미지들을 제공하기 위해 x 설명자를 사용하여 사용될 수 있습니다 (작은 이미지는 큰 이미지의 축소 버전입니다).

이미지의 렌더링된 크기가 뷰포트 너비에 따라 다르지만 (뷰포트 기반 선택) art direction과 함께 사용될 수 있는 경우 x 설명자는 적절하지 않습니다.

<h2>From today’s featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg"
      srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
      alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

유저 에이전트는 사용자의 화면의 픽셀 밀도, 확대 수준, 사용자의 네트워크 상태들 같은 다른 요소들에 따라 주어진 리소스들 중 어떤 것을 선택할 수 있습니다.

srcset 속성(attribute)을 아직 이해하지 못하는 이전의 유저 에이전트들과의 하위 호환성을 위해, URL 중 하나는 img 요소(element)의 src 속성(attribute)에 명시됩니다. 이것은 이전 유저 에이전트들에서조차도 유용하게 (아마도 사용자가 원하는 것보다 낮은 해상도 일지라도) 표시되는 것을 야기할 것입니다. 새로운 유저 에이전트들에 대해, src 속성(attribute)은 마치 srcset1x 설명자로 명시된 것 처럼 리소스 선택에 참여합니다.

이미지의 렌더링 되는 크기는 유저 에이전트가 이미지가 다운로드 되기 전에 이미지에 대한 공간을 할당하는 것을 허용하는 widthheight 속성(attribute)들에 주어집니다.

뷰포트 기반 선택

srcsetsizes 속성(attribute)들은 w 설명자를 사용하여, 크기가 다른 여러 이미지를 제공하는데 사용될 수 있습니다 (작은 이미지는 큰 이미지의 축소 버전입니다).

이 예에서, 배너 이미지는 (적절한 CSS를 사용하여) 전체 뷰포트 너비를 차지합니다.
<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
    src="wolf-400.jpg" alt="The rad wolf"></h1>

유저 에이전트는 명시된 w 설명자와 sizes 속성(attribute)에 명시된 렌더링 되는 크기로부터 각 이미지의 실질적인 픽셀 밀도를 계산할 것입니다. 그 후 사용자의 화면의 픽셀 밀도, 확대 수준, 사용자의 네트워크 조건들과 같은 가능한 다른 요인들에 따라 주어진 리소스 중 어느 것을 선택할 수 있습니다.

사용자의 화면이 320 CSS 픽셀 너비라면, 이것은 wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x를 명시하는 것과 동등합니다. 반면에, 사용자의 화면이 1200 CSS 픽셀 너비라면, 이것은 wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x을 명시하는 것과 동등합니다. w 설명자와 sizes 속성(attribute)을 사용하는 것에 의해, 유저 에이전트는 사용자의 디바이스의 크기에 상관없이 다운로드할 적절한 이미지 소스를 선택할 수 있습니다.

하위 호환성을 위해, URL들 중 하나는 img 요소(element)의 src 속성(attribute)에 명시됩니다. 새로운 유저 에이전트들에서, src 속성(attribute)은 srcset 속성(attribute)이 w 설명자들을 사용하는 경우 무시됩니다.

이 예에서, sizes 속성(attribute)은 기본 값이 100vw이기 때문에 생략될 수 있습니다.

이 예에서, 웹 페이지는 뷰포트의 너비에 따른 세 가지 레이아웃들을 가집니다. 좁은 레이아웃은 이미지들의 한 개 열을 (각 이미지의 너비가 약 100%) 가지고, 중간 레이아웃은 이미지들의 두 개 열을 (각 이미지의 너비가 약 50%) 가지며, 가장 넓은 레이아웃은 이미지들의 세 개 열과 일부 페이지 여백을 (각 이미지의 너비는 약 33%) 가집니다. 이 레이아웃들은 뷰포트가 각각 폭 30em과 폭 50em 인 경우에 나뉩니다.
<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
src="swing-400.jpg" alt="Kettlebell Swing">

sizes 속성(attribute)은 30em50em에 레이아웃 브레이크포인트들을 설정하고, 이 브레이크포인트들 사이의 이미지 크기들을 100vw, 50vw, calc(33vw - 100px)로 선언합니다. 이 크기들은 CSS에 명시된 실제 이미지 너비와 정확하게 일치해야(have to) 할 필요는 없습니다.

유저 에이전트는 true로 평가되는 <media-condition> (괄호 안의 부분)를 가진 첫 번째 항목을 사용하거나, 모든 것이 false로 평가되는 경우 마지막 항목 (calc(33vw - 100px))를 사용하여 sizes 속성(attribute)으로부터 너비를 선택할 것입니다.

예를 들어, 뷰포트 너비가 29em이라면, (max-width: 30em)는 true로 평가되고 100vw가 사용되고, 따라서 리소스 선택의 목적에 대한 이미지 크기는 29em입니다. 뷰포트 너비가 32em이라면, (max-width: 30em)는 false로 평가되고 (max-width: 50em)가 true로 평가되며 50vw가 사용되고, 따라서 리소스 선택의 목적에 대한 이미지 크기는 16em입니다(뷰포트 너비의 반). 약간 넓은 뷰포트는 레이아웃이 다르기 때문에 더 작은 이미지를 야기하는 것에 주목하세요.

유저 에이전트는 이후 실질적인 픽셀 밀도를 계산하고 이전 예와 마찬가지로 적절한 리소스를 선택할 수 있습니다.

Art direction 기반 선택

media 속성(attribute)을 가진 picture 요소(element)와 source 요소(element)는 이미지 콘텐트가 다른 여러 이미지들을 제공하는데 사용될 수 있습니다(예를 들어 작은 이미지는 큰 이미지의 잘려진 버전이 될 수 있습니다.).

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="The wolf runs through the snow.">
</picture>

유저 에이전트는 media 속성(attribute) 내 미디어쿼리와 일치하는 첫 번째 source 요소(element)를 선택할 것이고, 이후 그것의 srcset 속성(attribute)으로부터 적절한 URL을 선택할 것입니다.

이미지의 렌더링 되는 크기는 선택되는 리소스에 따라 달라집니다. 유저 에이전트가 다운로드 된 이미지를 소유하기 전에 사용할 수 있는 치수를 명시하기 위해 CSS가 사용될 수 있습니다.

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }
이 예는 art direction기기 픽셀 비율 기반 선택을 결합합니다. 뷰포트의 반을 차지하는 배너는 넓은 화면들에 대한 하나와 좁은 화면들에 대한 하나 두 가지 버전들로 제공됩니다.
<h1>
  <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="The Breakfast Combo">
  </picture>
</h1>
이미지 형식 기반 선택

source 요소(element)에 type 속성(attribute)이 다른 형식들로 여러 이미지들을 제공하는데 사용될 수 있습니다.

<h2>From today’s featured article</h2>
<picture>
  <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
  <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
  <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

이 예에서, 유저 에이전트는 지원되는 MIME 타입을 가지는 type 속성(attribute)을 가진 첫 번째 source를 선택할 것입니다. 유저 에이전트가 WebP 이미지들을 지원한다면, 첫 번째 source 요소(element)가 선택됩니다. 그렇지 않고, 유저 에이전트가 JPEG XR 이미지들을 지원한다면, 두 번째 source 요소(element)가 선택 될 것입니다. 그 형식들 중 어떤 것도 지원되지 않는다면, img 요소(element)가 선택 될 것입니다.

4.7.2. 종속성

미디어 쿼리 [MEDIAQ]

<media-condition>

CSS 값과 단위 [CSS-VALUES]

<length>

CSS 구문 [CSS-SYNTAX-3]

콤마로 구분된 컴포넌트 값들의 목록 해석

컴포넌트 값

<whitespace-token>

4.7.3. picture 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
선택적으로 스크립트 지원 요소(element)들과 섞어서, 한 개 img 요소(element)가 뒤따르는 0개 이상의 source 요소(element)들.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
interface HTMLPictureElement : HTMLElement {};

picture 요소(element)는 화면 픽셀 밀도, 뷰포트 크기, 이미지 형식, 다른 요인들에 기반하여, 작성자들이 사용할 이미지 리소스에 대해 유저 에이전트에게 선언적으로 제어하거나 힌트를 제공할 수 있도록 허용하기 위해 그것의 포함된 img 요소(element)에 여러 소스들을 제공하는 컨테이너 입니다. 이것은 그것의 자식을 나타냅니다.

picture 요소(element)는 유사하게 보이는 videoaudio 요소(element)들과는 다소 다릅니다. 그들 모두가 source 요소(element)들을 포함하는 반면, source 요소(element)의 src 속성(attribute)은 요소(element)가 picture 요소(element)에 중첩되어 있는 경우 의미(meaning)를 가지지 않고, 리소스 선택 알고리즘이 다릅니다. 뿐만 아니라, picture 요소(element) 자체는 어떤 것도 표시하지 않습니다; 단지 여러 URL들 중에서 선택할 수 있는 포함된 img 요소(element)에 대한 컨텍스트를 제공할 뿐입니다.

4.7.4. picture 요소(element)와 함께 사용되는 경우 source 요소(element)

카테고리:
source 요소(element)와 동일.
이 요소(element)가 사용될 수 있는 컨텍스트:
picture 요소(element)의 자식으로, img 요소(element) 이전에.
콘텐트 모델:
source 요소(element)와 동일.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
srcset - 다른 상황들에 (예를 들어, 고해상도 디스플레이들, 작은 모니터들 등) 사용될 이미지들
sizes - 브레이크포인트들 사이의 이미지 크기들
media - 적용 가능한 매체
type - 삽입된 리소스의 유형
허용된 ARIA 역할(role) 속성(attribute) 값들:
없음
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
DOM 인터페이스:
partial interface HTMLSourceElement {
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString media;
};

이 섹션에서 작성 요구 사항들은 source 요소(element)가 picture 요소(element)인 부모를 가지는 경우에만 적용됩니다.

source 요소(element)는 작성자들이 img 요소(element)들에 대한 여러 대체 소스 세트들을 명시하는 것을 허용합니다. 이것은 그 자체로 아무 것도 나타내지 않습니다.

srcset 콘텐트 속성(attribute)은 존재해야(must) 하고, 각각 다음 것이 U+002C 콤마 문자 (,)로 구분되는 하나 이상의 이미지 후보 문자열들로 구성되어야(must) 합니다. 이미지 후보 문자열들이 설명자를 포함하지 않고 URL 이후 공백 문자들을 포함하지 않는다면, 다음 이미지 후보 문자열이 있다면 이것은 하나 이상의 공백 문자들로 시작해야(must) 합니다.

srcset 속성(attribute)이 너비 설명자를 사용하는 이미지 후보 문자열들을 가진다면, sizes 콘텐트 속성(attribute) 역시 존재해야(must)하고, 값은 유효한 소스 크기 목록이어야(must) 합니다.

media 콘텐트 속성(attribute) 역시 존재 할 수 있습니다. 존재한다면, 값은 유효한 미디어쿼리 목록을 포함해야(must) 합니다.

type 콘텐트 속성(attribute) 역시 존재할 수 있습니다. 존재한다면, 값은 유효한 MIME 타입이어야(must) 합니다. 이것은 유저 에이전트가 주어진 유형을 지원하지 않을 경우 다음 source 요소(element)로 건너뛰는 것을 허용하기 위해 소스 세트에 이미지들의 유형을 제공합니다.

type 속성(attribute)가 명시되지 않은 경우, 유저 에이전트는 다른 source 요소(element)를 가져온 이후 이미지 형식을 지원하지 않는 다는 것을 발견한다면 그것을 선택하지 않을 것입니다.

source 요소(element)가 다음 형제 source 요소(element)나 srcset 속성(attribute)이 명시된 img 요소(element)를 가지는 경우, 그것은 다음 중 적어도 하나를 가져야(must) 합니다:

src 속성(attribute)은 존재하지 않아야(must) 합니다.

IDL 속성(attribute)들 srcset, sizes, media는 동일한 이름의 각 콘텐트 속성(attribute)들을 반영 해야(must) 합니다.

4.7.5. img 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
양식(form) 관련 요소(element).
요소(element)가 usemap 속성(attribute)을 가진다면: 대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
없음
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
alt - 이미지들이 사용 가능하지 않은 경우 대체 텍스트
src - 리소스의 주소
srcset - 다른 상황들에서 (예를 들어, 고화질 디스플레이들, 작은 모니터들 등등) 사용할 이미지들
sizes - 브레이크포인트들 사이의 이미지 크기들
crossorigin - 요소(element)가 교차출처 요청들을 처리하는 방식
usemap - 사용할 이미지 맵의 이름
ismap - 이미지가 서버 사이드 이미지 맵인지의 여부
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
alt 속성(attribute) 값이 비어있는 (alt="") img 요소(element)에 대해서는 presentation 역할(role)만, 그렇지 않으면 모든 역할(role) 값.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
[NamedConstructor=Image(선택적으로 부호 없는 너비 길이, 선택적으로 부호 없는 높이 길이)]
interface HTMLImageElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString src;
  attribute DOMString srcset;
  attribute DOMString sizes;
  attribute DOMString? crossOrigin;
  attribute DOMString useMap;
  attribute boolean isMap;
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long naturalWidth;
  readonly attribute unsigned long naturalHeight;
  readonly attribute boolean complete;
  readonly attribute DOMString currentSrc;
};

img 요소(element)는 이미지와 그것의 폴백 콘텐트를 나타냅니다.

srcsrcset, 그리고 부모가 picture 요소(element)인 경우 앞선 형제 source 요소(element)의 srcset 속성(attribute)들에 의해 주어진 이미지는 삽입(embedded) 콘텐트입니다; alt 속성(attribute)의 값은 img 요소(element)의 폴백 콘텐트이고, 이미지를 처리할 수 없거나 이미지 로딩이 비활성화 된 사용자나 유저 에이전트들에 대한 동등한 콘텐트를 제공합니다.

이미지의 대체 표현들에 대한 요구사항은 다음 섹센에 기술됩니다.

src 속성(attribute)은 존재해야(must)하고, 선택적으로 애니메이트 되고, 페이지화 되거나 스크립트화 되지 않는 비상호작용 이미지 리소스를 참조하는 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

srcset 속성(attribute)도 존재 할 수 있습니다. 존재한다면, 그것의 값은 하나 이상의, U+002C 콤마 문자 (,)로 다음이 각각 분리된, 이미지 후보 문자열들로 구성되어야(must) 합니다. 이미지 후보 문자열들이 설명자들을 포함하지 않고 URL 이후 공백 문자를 가지지 않는다면, 다음 이미지 후보 문자열이 있다면 하나 이상의 공백 문자들로 시작해야(must) 합니다.

이미지 후보 문자열은 이 목록 아래에 기술된 추가적인 제약 사항들을 가지고 순서에 따라 다음 컴포넌트들로 구성됩니다:

  1. 0개 이상의 공백 문자들.
  2. 선택적으로 애니메이트 되고, 페이지화 되거나 스크립트화 되지 않은 비상호작용 이미지 리소스를 참조하는, U+002C 콤마 문자 (,)로 시작하거나 끝나지 않는 유효한 비어있지 않은 URL.
  3. 0개 이상의 공백 문자들.
  4. 다음 중 0개 이상:

  5. 0개 이상의 공백 문자들.

동일한 요소(element)에 대한 다른 이미지 후보 문자열너비 설명자 값과 동일한 너비 설명자 값을 가진 요소(element)에 대한 이미지 후보 문자열은 존재하지 않아야(must) 합니다.

동일한 요소(element)에 대한 다른 이미지 후보 문자열픽셀 밀도 설명자 값과 동일한 픽셀 밀도 설명자 값을 가진 요소(element)에 대한 이미지 후보 문자열은 존재하지 않아야(must) 합니다. 이 요구사항의 목적을 위해, 설명자들이 없는 이미지 후보 문자열1x 설명자를 가진 이미지 후보 문자열과 동등합니다.

source 요소(element)가 sizes 속성(attribute)을 가지거나 img 요소(element)가 sizes 속성(attribute)을 가진다면, 그 요소(element)에 대한 모든 이미지 후보 문자열을은 명시된 너비 설명자를 가져야(must) 합니다.

sourceimg 요소(element)에 대한 이미지 후보 문자열이 명시된 너비 설명자를 가진다면, 그 요소(element)에 대한 모든 다른 이미지 후보 문자열는 명시된 너비 설명자 역시 가져야(must) 합니다.

이미지 후보 문자열너비 설명자에 명시된 너비는 이미지 후보 문자열의 URL에 의해 주어진 리소스가 고유 너비를 가진다면 리소스의 고유 너비와 일치해야(must)합니다.

위 요구사항들은 이미지가 정적 비트맵(예를 들어, PNG, GIF, JPEG), 단일 페이지 벡터 문서 (단일 페이지 PDF, SVG 루트 요소(element)를 가진 XML 파일), 애니메이트 된 비트맵(APNG, animated GIF), 애니메이트 된 벡터 그래픽(선언전 SMIL 애니메이션을 사용하는 SVG 루트 요소(element)를 가진 XML 파일들), 등등 일 수 있다는 것을 의미합니다. 하지만, 이 정의들은 스크린트가 있는 SVG 파일들, 여러 페이지 PDF 파일들, 상호작용 MNG 파일들, HTML 문서들, 평문 문서들, 등등을 불가능하게 합니다. [PNG] [GIF] [JPEG] [PDF] [XML] [APNG] [SVG11] [MNG]

srcset 속성(attribute)가 존재한다면, sizes 속성(attribute)도 존재할 수 있습니다. 이 속성(attribute)이 존재한다면, 그 값은 유효한 소스 크기 목록이어야(must) 합니다.

유효한 소스 크기 목록은 다음 뭄법과 일치하는 문자열입니다: [CSS-VALUES] [MEDIAQ]

<source-size-list> = <source-size># [ , <source-size-value> ]? | <source-size-value>
<source-size> = <media-condition> <source-size-value>
<source-size-value> = <length>

<source-size-value>는 음수가 아니어야(must) 합니다.

관련되는 것에 대한 혼란을 방지하기 위해, 백분율은 <source-size-value>에 허용되지 않습니다. vw 단위가 viewport 너비에 연관된 크기로 사용될 수 있습니다.

img 요소(element)는 레이아웃 도구로 사용되지 않아야 합니다. 특히, 투명 이미지는 거의 의미를 전달하지 않고 문서에 유용한 어떠한 것을 거의 추가하지 않기 때문에, img 요소(element)들은 투명 이미지들을 표시하는데 사용되지 않아야(should) 합니다.


crossorigin 속성(attribute)는 CORS 설정 속성(attribute) 입니다. 그것의 목적은 교차 출처 접근을 허용하는 서드 파티 사이트들로부터 이미지를 canvas를 가지고 사용하도록 허용하는 것입니다.


img 요소(element)는 현재 요청보류 중인 요청을 가집니다. 현재 요청은 초기에 새로운 이미지 요청으로 설정됩니다. 보류 중인 요청은 초기에 null로 설정됩니다. 현재 요청은 보통 img 요소(element) 자체로 언급됩니다.

이미지 요청상태, 현재 URL, 이미지 데이터를 가집니다.

이미지 요청상태는 다음 중 하나입니다:

사용 불가
유저 에이전트가 이미지 데이터를 얻지 못했거나 이미지의 일부 혹은 모든 데이터를 얻었지만 이미지 치수들을 얻기에 이미지를 충분히 디코드 하지 못한 경우.
일부 사용 가능
유저 에이전트가 이미지 데이터의 일부를 얻었고 적어도 이미지 치수들이 사용 가능 한 경우.
완전히 사용 가능
유저 에이전트가 모든 이미지 데이터를 얻었고 적어도 이미지 치수들이 사용 가능한 경우.
깨짐
유저 에이전트가 얻을 수 있는 모든 이미지 데이터를 얻었지만, 이미지 치수들을 얻기에 충분히 디코드 될 수 없는 경우 (예를 들어, 이미지가 손상되었거나, 지원되지 않는 형식이거나, 얻어질 수 있는 데이터가 없는 경우).

이미지 요청현재 URL은 초기에 빈 문자열입니다.

이미지 요청이미지 데이터는 디코드 된 이미지 데이터입니다.

이미지 요청일부 사용 가능한 상태에 있거나 완전히 사용 가능한 상태에 있는 경우, 그것은 사용 가능하다고 불립니다.

이미지 요청은 초기에 사용 불가입니다.

img 요소(element)가 사용 가능한 경우, 너비가 이미지의 밀도 보정 고유 너비이고, 높이가 이미지의 밀도 보정 고유 높이이며, 모양이 이미지의 고유 모양인 페인트 소스를 제공합니다.

스크립팅이 비활성화 된 브라우징 컨텍스트에서, 유저 에이전트들은 즉시 혹은 요청 시 마다 이미지들을 얻을 수 있습니다. 스크립팅이 활성화 된 브라우징 컨텍스트에서, 유저 에이전트들은 즉시 이미지들을 얻어야(must) 합니다.

이미지들을 즉시 얻는 유저 에이전트는 img 요소(element)가 생성되거나 관련 변경들을 경험할 때마다, 애니메이션 재시작 플래그 설정이 명시된 경우 이 플래그를 가지고 즉시 img 요소(element)의 이미지 데이터를 업데이트해야(must) 합니다.

이미지들을 요청 시마다 얻는 유저 에이전트는 img 요소(element)가 사용 불가 상태에 있을 경우에 한하여 이미지 데이터가 요구 될 때마다 (즉, 요청 시 마다) img 요소(element)의 이미지 데이터를 업데이트 해야(must) 합니다. img 요소(element)가 관련 변경들을 경험할 경우, 유저 에이전트가 요청 시에 이미지를 얻기만 한다면, img 요소(element)는 사용 불가 상태를 반환해야(must) 합니다.

img 요소(element)에 대한 관련 변경들은 다음과 같습니다:

  • 요소(element)의 src, srcset, width, sizes 속성(attribute)들이 설정, 변경, 제거 되는 것.
  • 요소(element)의 src 속성(attribute)이 이전 값과 동일한 값으로 설정 되는 것. 이것은 이미지 데이터 업데이트 알고리즘을 위한 애니메이션 재시작 플래그를 설정해야(must) 합니다.
  • 요소(element)의 crossorigin 속성(attribute)의 상태가 변경되는 것.
  • 요소(element)가 picture 부모 요소(element)로 삽입되거나 picture 부모 요소(element)로부터 제거되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 source 요소(element)가 이전 형제로 삽입 되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 이전 형제였던 source 요소(element)가 제거 되는 것.
  • 요소(element)의 부모가 picture 요소(element)이고 이전 형제인 source 요소(element)가 그것의 srcset, sizes, media, type 속성(attribute)들이 설정, 변경, 제거 되는 것.
  • 요소(element)의 채택 단계들이 수행되는 것.

img 요소(element)는 초기에 null 이어야(must) 하는 마지막 선택 된 소스를 가집니다.

이미지 요청은 초기에 uyndefined여야(must) 하는, 현재 픽셀 밀도를 가집니다.

img 요소(element)가 1.0이 아닌 현재 픽셀 밀도를 가지는 경우, 요소(element)의 이미지 데이터는 그것의 해상도가 CSS 픽셀 당 기기 픽셀로, 현재 픽셀 밀도 였던 것처럼 취급되어야(must) 합니다. 이미지의 밀도 보정 고유 너비와 높이현재 픽셀 밀도를 고려한 이후의 고유 너비와 높이입니다.

예를 들어, CSS 인치 당 96 CSS 픽셀로 주어진 스크린은, 현재 픽셀 밀도가 3.125라면, 그것은 CSS 인치 당 96 × 3.125 = 300 기기 픽셀이 있음을 의미하고, 따라서 이미지 데이터가 300x600이라면, 그것은 300 ÷ 3.125 = 96 CSS 픽셀 x 600 ÷ 3.125 = 192 CSS 픽셀의 고유 치수들 을 가집니다. 2.0의 현재 픽셀 밀도과 (CSS 인치 당 192 기기 픽셀) 동일한 이미지 데이터 (300x600)을 가진 경우, 고유 치수들은 150x300 이 될 것입니다.

Document 객체는 사용 가능한 이미지들의 목록을 가져야(must) 합니다. 이 목록 내의 각 이미지는 절대 URL, CORS 설정 속성(attribute) 모드, 그리고 모드가 No CORS라면 출처로 구성되는 튜플에 의해 식별됩니다. 각 이미지는 뿐만 아니라 상위 계층 캐싱 무시 플래그를 가집니다. 유저 에이전트들은 하나의 Document 객체의 사용 가능한 이미지들의 목록으로부터 항목들을 언제든지 다른 곳으로 복사할 수 있지만 (예를 들어, Document가 생성 될 때, 유저 에이전트들은 다른 Document들에 로드되는 모든 이미지들에 그것을 추가할 수 있습니다), 그렇게 수행될 때 이 방법으로 복사된 항목들의 키들을 변경하지 않아야(must)하고, 복사된 항목들에 대한 상위 계층 캐싱 무시 플래그를 해제해야(must) 합니다. 유저 에이전트들은 언제든지 (예를 들어, 메모리를 절약하기 위해) 그 목록들로부터 이미지들을 제거 할 수도 있습니다. 유저 에이전트들은 상위 계층 캐싱 무시 플래그가 해제 된 경우 리소스에 대해 주어진 상위 계층 캐싱 의미에 (예를 들어, HTTP Cache-Control 응답 헤더) 적절하게 사용 가능한 이미지들의 목록에서 항목들을 제거해야(must) 합니다.

사용 가능한 이미지들 목록src 속성(attribute)을 이전에 로드된 URL로 변경할 때 동기적 전환을 활성화하고, HTTP당 캐싱을 허용하지 않는 경우에도 동일한 문서에서 이미지들을 재 다운로드하는 것을 방지하기 위해 의도되었습니다. 이전 이미지가 여전히 로딩 중인 동안 동일한 이미지를 다시 다운로드 하는 것을 방지하는데에는 사용되지 않습니다.

예를 들어, 리소스가 HTTP 응답 헤더 Cache-Control: must-revalidate를 가진다면, 유저 에이전트는 사용 가능한 이미지들 목록으로부터 그것을 제거할 것이지만 별도로 이미지 데이터를 유지할 수 있고, 서버가 204 No Content 상태로 응답한다면 그것을 사용할 수 있습니다.

유저 에이전트가 선택적으로 애니메이션 재시작 플래그 설정을 가지고, img 요소(element)의 이미지 데이터를 업데이트하기 위한 경우, 다음 단계들을 수행해야(must) 합니다:

  1. 요소(element)의 노드 문서활성 문서가 아니라면, 이 하위 단계들을 수행합니다:

    1. 병렬로 이 알고리즘을 수행하는 것을 계속합니다.
    2. 요소(element)의 노드 문서활성 문서일 때가지 대기합니다.
    3. img 요소에 대한 이 알고리즘의 다른 인스턴스가 이 인스턴스 이후에 시작되었다면 (그것이 중단되었고 더 이상 수행중이 아니라 하더라도), 이 단계들을 중단합니다.
    4. 이 알고리즘을 계속하기 위한 마이크로작업을 대기열에 넣습니다.
  2. 유저 에이전트가 이미지들을 지원하지 못하거나, 그것의 이미지들에 대한 지원이 비활성화 되었다면, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, 현재 요청사용 불가 상태로 설정하고, 보류 중인 요청을 null로 두고, 이 단계들을 중단합니다.
  3. 요소(element)가 srcsetpicture를 사용하지 않고 부모를 가지지 않거나 부모를 가지지만 picture 요소(element)가 아니고, 명시된 src 속성(attribute)을 가지며 그 값이 빈 문자열이 아니라면, selected source를 요소(element)의 src 속성(attribute)의 값으로 두고, selected pixel density를 1.0으로 둡니다. 그렇지 않으면 selected source를 null로 두고 selected pixel density를 undefined로 둡니다.

  4. img 요소(element)의 마지막 선택 된 소스selected source로 둡니다.
  5. selected source가 null이 아니라면, 이 하위 단계들을 수행합니다:

    1. 요소(element)에 관련하여, selected source해석하고, 결과를 absolute URL로 둡니다. 그것이 성공적이지 않다면, 이 단계들의 내부 설정을 중단합니다.
    2. key를 결과로 나온 절대 URL, img 요소(element)의 crossorigin 속성(attribute)의 모드, 그리고 그 모드가 No CORS가 아니라면 노드 문서출처로 구성되는 튜플로 둡니다.
    3. 사용 가능한 이미지들의 목록key에 대한 항목을 포함한다면, 이 하위 단계들을 수행합니다:

      1. 그 항목에 대한 상위 계층 캐싱 무시 플래그를 설정합니다.
      2. 현재 요청보류 중인 요청에 대한 이미지 요청을 중단 시킵니다.
      3. 보류 중인 요청을 null로 둡니다.
      4. 현재 요청이미지 데이터가 항목의 이미지 데이터이고 상태가 완전히 사용 가능 상태로 설정 된 새로운 이미지 요청으로 둡니다.
      5. 이미지의 표현을 적절하게 업데이트 합니다.
      6. 현재 요청현재 픽셀 밀도selected pixel density로 둡니다.
      7. 애니메이션 재시작이 설정되고, 현재 응답현재 URLabsolute URL로 변경하고, 이후 img 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시킨다면, 애니메이션을 재시작하기 위한 작업을 대기열에 넣습니다.
      8. 이미지 데이터 업데이트 알고리즘을 중단합니다.
  6. 이 알고리즘이 호출되는 작업이 계속되는 것을 허용하여, 병렬로 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 알릴 때까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션내 단계들은 ⌛로 표기됩니다.)
  7. ⌛ 이 img 요소(element)에 대한 이 알고리즘의 다른 인스턴스가 이 인스턴스 이후 시작되었다면 (그것이 중단되고 더 이상 수행 중이 아닐지라도), 이 단계들을 중단합니다.

    예를 들어, src, srcset, crossorigin 속성(attribute)가 연속적으로 모두 설정되어 있는 경우, 여러 요청들을 방지하기 위해, 오직 마지막 인스턴스만 적용됩니다.

  8. selected sourceselected pixel density를 각각 이미지 소스 선택으로부터 얻어진 결과 URL과 픽셀 밀도로 둡니다.

  9. selected source가 null이라면, 이 하위 단계들을 수행합니다:

    1. 현재 요청깨짐 상태로 설정하고, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 null로 둡니다.
    2. 현재 요청현재 ULR을 빈 문자열로 변경하기 위한 작업을 대기열에 넣고, 이후 요소(element)가 src 속성(attribute)을 가지거나 그것이 srcset이나 picture를 사용한다면, img 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시킵니다.
    3. ⌛ 이 알고리즘을 중단합니다.
  10. img 요소(element)에 loadstart라고 이름이 붙은 진행 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    ⌛ 요소(element)의 노드 문서에 관련하여, selected source해석하고, absolute URL결과 URL 문자열로 둡니다. 그것이 성공적이지 않다면, 이 하위 단계들을 수행합니다:

    1. 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시킵니다.
    2. 현재 요청깨짐 상태로 설정합니다.
    3. 보류 중인 요청을 null로 둡니다.
    4. 현재 요청현재 URLselected source로 변경하기 위한 작업을 대기열에 넣고, img 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시킨 후 img 요소(element)에 loadend라고 이름이 붙은 단순 이벤트를 발생시킵니다.
    5. 이미지 데이터 업데이트 알고리즘을 중단시킵니다.
  11. 보류 중인 요청이 null이 아니고, absolute URL보류 중인 요청현재 URL과 동일하다면, 이 단계들을 중단합니다.

    absolute URL현재 요청현재 URL과 동일하고, 현재 요청일부 사용 가능 상태에 있다면, 보류 중인 요청에 대한 이미지 요청을 중단시키고, 애니메이션 재시작이 설정되어 있다면 애니메이션을 재시작하기 위한 작업을 대기열에 넣고 이 단계들을 중단합니다.

    보류 중인 요청이 null이 아니라면, 보류 중인 요청에 대한 이미지 요청을 중단합니다.

    image request현재 URLabsolute URL인 새로운 이미지 요청으로 둡니다.

    현재 요청사용 불가 상태나 깨짐 상태에 있다면, 현재 요청image request로 둡니다. 그렇지 않으면 보류 중인 요청image request으로 둡니다.

    requestabsolute URL과 요소(element)의 crossorigin 콘텐트 속성(attribute)의 현재 상태가 주어지는 잠정적 CORS 요청을 생성한 결과로 둡니다.

    request클라이언트를 요소(element)의 노드 문서Window 객체의 환경 설정 객체유형을 "image"로 설정합니다.

    ⌛ 요소(element)가 srcsetpicture를 사용한다면, request개시자를 "imageset"로 설정합니다.

    request동일 출처 데이터 URL 플래그를 설정합니다.

    request가져옵니다(fetch). 페칭(fetch) 알고리즘의 이 인스턴스를 image request과 연관짓습니다.

    이 방식으로 얻어진 리소스가 있다면 이 리소스는 image request이미지 데이터입니다. 그것은 CORS 동일 출처이거나 CORS 교차 출처일 수 있습니다. 이것은 이미지 자체의 출처에 영향을 미칩니다 (예를 들어, canvas에 사용되는 경우).

    이미지를 가져오는 것(fetch)은 리소스가 가져와(fetch) 지자마자 (아래 정의된) 네트워킹 작업 소스에 의해 대기열에 넣어진 작업이 수행되었을 때까지 요소(element)의 노드 문서로드 이벤트를 지연시켜야(must) 합니다.

    불행히도, 이것은 사용자의 로컬 네트워크의 기본적인 포트 조사를 수행하는데 사용될 수 있습니다 (특히 스크립트와 함께, 그러한 공격을 수행하기 위해 실제로 스크립팅이 필요한 것은 아니지만). 유저 에이전트는 이 공격을 완화하기 위해 위에 설명된 것들보다 더 엄격한 교차 출처 접근 제어 정책들을 구현할 수 있지만, 불행히도 그러한 정책들은 일반적으로 현재 사용되는 웹 콘텐트와 호환되지 않습니다.

    리소스가 CORS 교차 출처라면, 이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업img 요소(element)에 progress라고 이름이 붙은 진행 이벤트를 발생시켜야(must) 합니다.

  12. 병렬로 남은 단계들을 계속하되, 가져오는(fetch) 것에서 데이터 누락 없이 동기 섹션 종료시킵니다.
  13. 가능한 빨리, 다음 목록에서 처음 적절한 항목으로 건너뜁니다:

    리소스 유형이 multipart/x-mixed-replace라면

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진 다음 작업은 다음 단계들을 수행해야(must) 합니다:

    1. image request보류 중 요청이고 적어도 하나의 본문 부분이 완전히 디코드되었다면, 현재 요청에 대한 이미지 요청을 중단하고 보류 중인 요청을 현재 요청으로 업그레이드 합니다.

    2. 그렇지 않고, image request보류 중인 요청이고 유저 에이전트가 image request의 이미지가 일부 치명적인 방법으로 손상되어 이미지의 치수들을 얻을 수 없다고 결정할 수 있다면, 현재 요청에 대한 이미지 요청을 중단하고, 보류 중인 요청을 현재 요청으로 업그레이드하고, 현재 요청의 상태를 깨짐으로 설정합니다.

    3. 그렇지 않고, image request현재 요청이고, 그것이 사용 불가 상태에 있으며, 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있다면, 현재 요청의 상태를 일부 사용 가능으로 설정합니다.

    4. 그렇지 않고, image request현재 요청이고, 그것이 사용 불가 상태에 있으며, 유저 에이전트가 image request의 이미지가 일부 치명적인 방법으로 손상되어 치수들을 얻을 수 없다고 결정할 수 있다면, 현재 요청의 상태를 깨짐으로 설정합니다.

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업은 이미지의 표현을 업데이트해야(must) 하지만, 각 새로운 본문 부분이 들어올 때 마다, 그것은 이전 이미지를 교체해야(must) 합니다. 하나의 본문 부분이 완전히 디코드되면, 유저 에이전트는 img 요소(element)를 완전히 사용 가능으로 설정하고 img 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다.

    progressloadend 이벤트들은 multipart/x-mixed-replace 이미지 스트림들에 대해 발생되지 않습니다.

    리소스 유형과 데이터가 지원되는 이미지 형식에 일치한다면, 아래 기술된 대로

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진 다음 작업은 다음 단계들을 수행해야(must) 합니다:

    1. 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있고 image request보류 중인 요청이라면, image request의 상태를 일부 사용 가능으로 설정합니다.

    2. 그렇지 않고, 유저 에이전트가 image request의 이미지의 너비와 높이를 결정할 수 있고 image request현재 요청이라면, img 요소(element)의 표현을 적절하게 업데이트하고 image request의 상태를 일부 사용 가능으로 설정합니다.

    3. 그렇지 않고, 유저 에이전트가 image request의 이미지가 어떤 치명적 오류로 이미지 치수들을 얻을 수 없다고 결정할 수 있고, image request보류 중인 요청이라면, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, 보류 중인 요청을 현재 요청으로 업그레이드하고, 현재 요청깨짐 상태로 설정하고, img 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시키고, img 요소(element)에 loadend라고 이름이 붙은 단순 이벤트를 발생시키고, 이 단계들을 중단합니다.

    4. 그렇지 않고, 유저 에이전트가 image request의 이미지가 어떤 치명적 오류로 이미지 치수들을 얻을 수 없다고 결정할 수 있고, image request현재 요청이라면, image request에 대한 이미지 요청을 중단시키고, img 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시키고, img 요소(element)에 loadend라고 이름이 붙은 단순 이벤트를 발생시키고, 이 단계들을 중단합니다.

    이미지가 가져와지는(fetch) 동안 네트워킹 작업 소스에 의해 대기열에 넣어진작업, 그리고 각 차후 작업들은, image request현재 요청이라면, 이미지의 표현을 적절하게 업데이트 해야(must) 합니다 (예를 들어, 이미지가 점진적 JPEG라면, 각 패킷은 이미지의 해상도를 향상시킬 수 있습니다).

    게다가, 리소스가 가져와졌을(fetch) 때 네트워킹 작업 소스에 의해 대기열에 넣어진 마지막 작업은 추가적으로 이 단계들을 수행해야(must) 합니다:

    1. image request보류 중인 요청이라면, 현재 요청에 대한 이미지 요청을 중단시키고, 보류 중인 요청을 현재 요청으로 업그레이드하고, img 요소(element)의 표현을 적절하게 업데이트 합니다.
    2. image request완전히 사용 가능 상태로 설정합니다.
    3. key를 사용하여, 상위 계층 캐싱 무시 플래그 설정과 함께, 이미지를 사용 가능한 이미지들의 목록에 추가합니다.
    4. image request 내 리소스에 따라, img 요소에 load라고 이름이 붙은 진행 이벤트나 단순 이벤트를 발생시킵니다.
    5. image request 내 리소스에 따라, img 요소에 loadend라고 이름이 붙은 진행 이벤트나 단순 이벤트를 발생시킵니다.
    그렇지 않으면

    이미지 데이터가 지원되는 파일 형식에 없습니다; 유저 에이전트는 image request깨짐 상태로 설정하고, 현재 요청보류 중인 요청에 대한 이미지 요청을 중단시키고, image request보류 중인 요청이라면 보류 중인 요청을 현재 요청으로 업그레이드하고, 그 후 먼저 img 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시키기고 이후 img 요소(element)에 loadend라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

이미지 요청 image request에 대해 이미지 요청을 중단시키는 것은 다음 단계들을 수행하는 것을 의미합니다:

  1. image request이미지 데이터가 있다면 무시합니다.
  2. 그 알고리즘에 의해 생성된 모든 보류 중인 작업들을 폐기하여, image request에 대한 페칭(fetching) 알고리즘의 모든 인스턴스를 중단합니다.

img 요소(element)에 대한 보류 중인 요청을 현재 요청으로 업그레이드하는 것은 다음 단계들을 수행하는 것을 의미합니다:

  1. img 요소(element)의 현재 요청보류 중인 요청으로 둡니다.
  2. img 요소(element)의 보류 중인 요청을 null로 둡니다.

리소스 r에 따라 요소(element) etype이라고 이름이 붙은 진행 이벤트나 단순 이벤트를 발생시키는 것은 rCORS 동일 출처라면 etype이라고 이름이 붙은 진행 이벤트를 발생시키고, 그렇지 않으면 etype이라고 이름이 붙은 단순 이벤트를 발생시키는 것을 의미합니다.

유저 에이전트가 요소(element) x에 대한 위 알고리즘을 수행하는 동안, 그 요소(element)가 그것의 Document에 없더라도, 요소(element)의 노드 문서로부터 요소(element) x까지 강한 참조가 있어야(must) 합니다.

img 요소(element)는 명시된 srcset 속성(attribute)를 가지거나 picture 요소(element)인 부모를 가진다면 srcsetpicture를 사용한다라고 합니다.

img 요소(element)가 완전히 사용 가능 상태에 있 유저 에이전트가 오류 없이 미디어 데이터를 디코드할 수 있다면, img 요소(element)는 완전히 디코드 가능하다고 합니다.

이미지가 성공적으로 가져와(fetch)졌는지 아닌지는 (예를 들어, 응답 상태들이 ok 상태들이었는지) 이미지의 유형과 그것이 유효한 이미지인지 아닌지를 결정하는 중에는 무시되어야(must) 합니다.

이것은 오류 응답으로 이미지들을 반환하게 하는 것을 허용하고 그것들을 표시할 수 있습니다.

유저 에이전트는 official type을 제공하는 이미지의 연관된 Content-Type 헤더들을 가지고, 이미지의 유형을 결정하는데 이미지 스니핑 규칙들을 적용해야(should) 합니다. 이 규칙들이 적용되지 않았다면, 이미지의 유형은 이미지의 연관된 Content-Type 헤더들에 의해 주어진 유형이어야(must) 합니다.

유저 에이전트들은 img 요소(element)로 이미지가 아닌 리소스들을 지원하지 않아야(must) 합니다 (예를 들어, 루트 요소(element)가 HTML 요소(element)인 XML 파일들). 유저 에이전트들은 이미지 리소스에 삽입된 실행 가능한 코드를 (예를 들어, 스크립트) 수행하지 않아야(must) 합니다. 유저 에이전트들은 여러 페이지 리소스의 (예를 들어, PDF 파일) 첫 번째 페이지만을 표시해야(must) 합니다. 유저 에이전트들은 리소스가 상호 작용 방식으로 동작하는 것을 허용하지 않아야(must) 하지만, 리소스 내 애니메이션은 수행해야(should) 합니다.

이 명세는 지원되는 이미지 유형들을 명시하지 않습니다.


img 요소(element)는 소스 세트와 연관됩니다.

소스 세트는 0개 이상의 이미지 소스들소스 크기의 정렬된 집합입니다.

이미지 소스URL과, 선택적으로 밀도 설명자 혹은 너비 설명자입니다.

소스 크기<source-size-value>입니다. 소스 크기뷰포트와 관련된 단위를 가진다면, 그것은 img 요소(element)의 문서의 뷰포트와 관련하여 해석되어야(must) 합니다. 다른 단위들은 미디어 쿼리 내의 것와 동일하게 해석되어야(must) 합니다. [MEDIAQ]

주어진 img 요소(element) el에 대해 이미지 소스 선택이 요청되는 경우, 유저 에이전트들은 다음을 수행해야(must) 합니다:

  1. el에 대해 소스 세트를 업데이트합니다.
  2. el소스 세트가 비어있다면, URL로서 null을, 픽셀 밀도로 undefined를 반환하고 이 단계들을 중단합니다.
  3. 그렇지 않으면, el소스 세트를 취하고 그것을 source set로 둡니다.
  4. source setbsource set 내 앞선 항목 a와 동일한 연관된 밀도 설명자를 가진다면, 항목 b를 제거합니다. source set에 앞선 항목과 동일한 연관된 밀도 설명자를 가지는 항목이 없을 때까지 이 단계를 반복합니다.
  5. 유저 에이전트 특정 방식으로, source set로부터 이미지 소스하나를 선택합니다. 이것을 selected source로 둡니다.
  6. selected source과 그것의 연관된 픽셀 밀도를 반환합니다.

주어진 img 요소(element) el에 대해 소스 세트 업데이트가 요청되는 경우, 유저 에이전트는 다음을 수행해야(must) 합니다:

  1. el소스 세트를 빈 소스 세트로 설정합니다.
  2. el이 부모 노드를 가지고 그것이 picture 요소(element)라면, elements를 연관된 순서를 고정시켜, el의 부모 노드의 자식 요소(element)들을 포함하는 배열로 둡니다. 그렇지 않으면, elementsel만 포함하는 배열로 둡니다.
  3. elwidth 속성(attribute)을 가지고, 치수 값 해석에 대한 규칙 을 사용하여 그 속성(attribtue)의 값을 해석한 것이 오류나 퍼센트 값을 생성하지 않는다면, width를 반환된 정수 값으로 둡니다. 그렇지 않으면, width를 null로 둡니다.
  4. 각 항목 child에 대해 다음을 수행하여, elements를 반복합니다:

    1. childel라면:

      1. childsrcset 속성(attribute)을 가진다면, child의 srcset 속성(attribute)을 해석하고 반환 된 소스 세트source set로 둡니다. 그렇지 않으면, source set를 빈 소스 세트로 둡니다.
      2. 폴백 너비 width를 가지고 child의 sizes 속성(attribute)을 해석하고, source set소스 크기를 반환된 값으로 둡니다.
      3. child가 값이 빈 문자열이 아니고 source set가 1의 밀도 설명자 값을 가진 이미지 소스를 포함하지 않는 src 속성(attribute)을 가지고, 너비 설명자가 있는 이미지 소스가 없다면, childsrc 속성(attribute)을 source set에 추가(append) 합니다.
      4. source set소스 밀도를 정규화합니다.
      5. el소스 세트source set로 둡니다.
      6. 이 알고리즘을 중단합니다.
    2. childsource 요소(element)가 아니라면, 다음 자식에 대해 계속합니다. 그렇지 않으면, childsource 요소(element)입니다.
    3. childsrcset 속성(attribute)을 가지지 않으면, 다음 자식에 대해 계속합니다.
    4. childsrcset 속성(attribute)을 해석하고 반환된 소스 세트source set로 둡니다.
    5. source set가 0개의 소스 세트를 가진다면, 다음 자식에 대해 계속합니다.
    6. childmedia 속성(attribute)을 가지고 그 값이 환경에 일치하지 않으면, 다음 자식에 대해 계속합니다.
    7. 폴백 너비 width를 가지고 childsizes 속성(attribute)을 해석하고, source set소스 크기를 반환된 값으로 둡니다.
    8. childtype 속성(attribute)을 가지고, 그 값이 알 수 없거나 지원되지 않는 MIME 타입이라면, 다음 자식에 대해 계속합니다.
    9. source set소스 밀도를 정규화합니다.
    10. el소스 세트source set으로 둡니다.
    11. 이 알고리즘을 중단합니다.

img 요소(element)는 이미지 소스를 선택하기 위해 다른 (유효하지 않은) 요소(element)들을 무시하여, 동일한 picture 요소(element) 내 다른 img 요소(element)들이나, 관련된 img 요소(element)의 형제들을 따르는 source 요소(element)들을 포함하여, 독립적으로 그것의 이전 형제 source 요소(element)들과 img 요소(element) 자체를 고려합니다.

요소(element)로부터 srcset 속성(attribute) 해석이 from an element, 요청 되는 경우, 다음과 같이 요소(element)의 srcset의 값을 해석합니다:

  1. input을 이 알고리즘에 전달된 값으로 둡니다.
  2. position을 초기에 문자열의 시작을 가리키는 input 내 포인터로 둡니다.
  3. candidates를 초기에 빈 소스 세트로 둡니다.
  4. 분할 반복: 공백 문자들이나 U+002C 콤마 문자들인 일련의 문자들을 수집합니다. U+002C 콤마 문자들이 수집되었다면, 그것은 해석 오류입니다.
  5. positioninput의 끝을 지났다면, candidates를 반환하고 이 단계들을 중단합니다.
  6. 공백 문자들이 아닌 일련의 문자들을 수집하고, 그것을 url로 둡니다.
  7. descriptors를 새로운 빈 목록으로 둡니다
  8. url이 U+002C 콤마 문자 (,)로 끝난다면, 이 하위 단계들을 따릅니다:

    1. url로부터 뒤따르는 002C 콤마 문자들을 제거합니다. 이것이 여러 문자를 제거했다면, 그것은 해석 오류입니다.

    그렇지 않으면, 이 하위 단계들을 따릅니다:

    1. Descriptor tokenizer: 여백을 건너뜁니다.
    2. current descriptor를 빈 문자열로 둡니다.
    3. state설명자 안에 둡니다.
    4. cposition에 위치한 문자로 둡니다. state의 값에 따라 다음을 수행합니다. 이 단계의 목적에 따라, "EOF"는 positioninput의 끝을 지났음을 나타내는 특수한 문자입니다.

      설명자 내부

      c의 값에 따라 다음을 수행합니다:

      공백 문자
      current descriptor가 비어있지 않다면, current descriptordescriptors에 추가(append)하고 current descriptor를 빈 문자열로 둡니다. state다음 설명자로 설정합니다.
      U+002C 콤마 (,)
      positioninput 내 다음 문자로 전진시킵니다. current descriptor가 비어있지 않다면, current descriptordescriptors에 추가(append)합니다. 설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      U+0028 왼쪽 괄호 (()
      ccurrent descriptor에 추가(append)합니다. state괄호(parens) 내부로 설정합니다.
      EOF
      current descriptor이 비어있지 않다면, current descriptordescriptors에 추가(append)합니다. 설명자 해석으로 라벨링된 단계로 건너뜁니다.
      그 밖에 다른 것들
      ccurrent descriptor에 추가(append) 합니다.
      괄호(parens) 내부

      c의 값에 따라 다음을 수행합니다:

      U+0029 오른쪽 괄호 ())
      ccurrent descriptor에 추가(append) 합니다. state설명자 내부로 설정합니다.
      EOF
      current descriptordescriptors에 추가(append) 합니다. 설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      그 밖에 다른 것들
      ccurrent descriptor에 추가(append) 합니다.
      설명자 이후

      c의 값에 따라 다음을 수행합니다:

      공백 문자
      이 상태에 머무릅니다.
      EOF
      설명자 해석으로 라벨링 된 단계로 건너뜁니다.
      그 밖에 다른 것들
      state설명자 내부로 설정합니다. positioninput이전 문자로 설정합니다.

      positioninput 내 다음 문자로 전진시킵니다. 이 하위 단계를 반복합니다.

      향후 추가되는 것들과 호환이 되기 위해, 이 알고리즘은 여러 설명자들과 괄호를 가진 설명자들을 지원합니다.

  9. 설명자 해석: errorno로 둡니다.
  10. widthabsent로 둡니다.
  11. densityabsent로 둡니다.
  12. future-compat-habsent로 둡니다.
  13. descriptors 내 각 설명자에 대해, 다음 목록으로부터 첫 적절한 단계의 세트를 수행합니다:

    설명자가 U+0077 라틴 소문자 W가 뒤따르는 유효한 음이 아닌 정수로 구성된다면
    1. 유저 에이전트가 sizes 속성(attribute)을 지원하지 않는다면, erroryes로 둡니다.

      지침을 따르는 유저 에이전트는 sizes 속성(attribute)을 지원할 것입니다. 하지만, 유저 에이전트들은 일반적으로 실제로는 점진적인 방식으로 기능을 구현하고 제공합니다.

    2. widthdensity가 모두 absent가 아니라면, erroryes로 둡니다.
    3. 음이 아닌 정수 해석에 대한 규칙을 설명자에 적용합니다. 결과가 0이라면, erroryes로 둡니다. 그렇지 않으면, width를 그 결과로 둡니다.
    설명자가 U+0078 라틴 소문자 X가 뒤따르는 유효한 부동소수점 수로 구성된다면
    1. width, density, future-compat-h가 모두 absent가 아니라면, erroryes로 둡니다.
    2. 부동 소수점 수 값 해석에 대한 규칙을 설명자를 적용합니다. 결과가 0보다 작다면, erroryes로 둡니다. 그렇지 않으면, density를 그 결과로 둡니다.

      density가 0이라면, 고유 치수들은 무한대가 될 것입니다. 유저 에이전트들은 하드웨어 제한사항들 조항에 따라 허용된 큰 이미지들을 렌더링하는데 한계가 있을 것으로 예상됩니다.

    설명자가 U+0068 라틴 소문자 H가 뒤따르는 유효한 음이 아닌 정수로 구성된다면

    이것은 해석 오류입니다.

    1. future-compat-hdensity가 모두 absent가 아니라면, erroryes로 둡니다.
    2. 음이 아닌 정수 해석에 대한 규칙을 설명자에 적용합니다. 결과가 0이라면, erroryes로 둡니다. 그렇지 않으면, future-compat-h를 그 결과로 둡니다.
    그 밖에 다른 것들
    erroryes로 둡니다.
  14. future-compat-habsent가 아니고 widthabsent라면, erroryes로 둡니다.
  15. error가 여전히 no라면, URL이 url이고 widthabsent가 아니라면 너비 widthdensityabsent가 아니라면 픽셀 밀도가 density와 연관된, 새로운 이미지 소스candidates에 추가(append) 합니다. 그렇지 않으면 해석 오류가 있습니다.
  16. 분할 반복으로 라벨링 된 단계로 돌아갑니다.

요소(element)에 대해 크기 속성(attribute)을 해석하도록 요청 될 경우, 요소(element)의 sizes 속성(attribute)의 값으로부터 (속성(attribute)이 없다면, 빈 문자열로부터) 컴포넌트 값들의 콤마로 분리된 목록을 해석하고, unparsed sizes list를 그 결과로 둡니다. [CSS-SYNTAX-3]

unparsed sizes list 내 각 unparsed size에 대해:

  1. unparsed size의 끝에서 모든 연속된 <whitespace-token>들을 제거합니다. unparsed size가 현재 비어있다면, 그것은 해석 오류입니다; 이 알고리즘의 다음 반복으로 계속합니다.
  2. unparsed size 내 마지막 컴포넌트 값이 유효한 음이 아닌 <source-size-value>라면, size를 그것의 값으로 두고 unparsed size로부터 컴포넌트 값을 제거합니다. calc() 함수 이외의 CSS 함수는 유효하지 않습니다. 그렇지 않으면 해석 오류가 있습니다; 이 알고리즘의 다음 반복으로 계속합니다.
  3. unparsed size의 끝에서 모든 연속된 <whitespace-token>들을 제거합니다. unparsed size가 현재 비어있다면, size를 반환하고 이 알고리즘을 나갑니다. 이것이 unparsed sizes list의 마지막 항목이 아니었다면, 그것은 해석 오류입니다.
  4. unparsed size 내 나머지 컴포넌트 값들<media-condition>로 해석합니다. 정확하게 해석하지 않거나, 정확하게 해석하지만 <media-condition>가 false로 평가된다면, 이 알고리즘의 다음 반복으로 계속합니다. [MEDIAQ]
  5. size를 반환하고 이 알고리즘을 나갑니다.

위 알고리즘이 반환하는 size 값 없이 unparsed sizes list를 소진한다면, 이 단계들을 따릅니다:

  1. width가 null이 아니라면, 값 width과 단위 px을 가진 <length>를 반환합니다.
  2. 100vw을 반환합니다.

위 알고리즘들에 대한 해석 오류가 입력과 요구사항들 사이의 치명적이지 않은 불일치를 나타냅니다. 유저 에이전트들은 어떻게든 해석 오류들을 노출하도록 권장됩니다.

유효한 소스 크기 목록이 (<media-condition>를 수반하지 않고) <source-size-list> 내 마지막 항목으로 텅 빈 <source-size-value>만을 포함하는 동안, 해석 알고리즘은 기술적으로 목록 내 어느 지점에나 허용되고, 목록 내 이전 항목들이 사용되지 않았다면 즉시 사이즈로 그것을 받아들일 것입니다. 이것은 미래 확장들을 가능하게 하는 것이고, 마지막 쉼표와 같은 단순한 작성자 오류들로부터 보호합니다.

이미지 소스는 모든 수반하는 그것의 URL에 밀도 설명자나 너비 설명자를 가지거나 어떤 설명자도 가지지 않을 수 있습니다. 소스 세트를 정규화 하는 것은 모든 이미지 소스에 밀도 설명자를 제공합니다

소스 세트 source set소스 밀도 정규화가 요청 되는 경우, 유저 에이전트는 다음을 수행해야(must) 합니다:

  1. source sizesource set소스 크기로 둡니다.
  2. source set 내 각 이미지 소스에 대해:

    1. 이미지 소스가 밀도 설명자를 가진다면, 다음 이미지 소스로 계속합니다.
    2. 그렇지 않고, 이미지 소스너비 설명자를 가진다면, 너비 설명자너비 설명자의 값을 소스 크기로 나눈 값과 x 단위로 교체합니다.

      소스 크기가 0이라면, 밀도는 고유 치수들이 0 x 0이 되는 결과를 낳는 무한대가 될 것입니다.

    3. 그렇지 않으면, 이미지 소스1x의 밀도 설명자를 제공합니다.

유저 에이전트는 환경의 변화에 반응하도록 img 요소(element)의 이미지를 갱신하기 위해 언제든지 다음 알고리즘을 수행할 수 있습니다. (유저 에이전트들은 이 알고리즘을 전혀 수행할 필요가 없습니다; 예를 들어, 사용자가 더 이상 페이지를 보고 있지 않다면, 유저 에이전트는 사용자가 사용할 이미지를 결정하기 전에, 그 동안에 환경이 다시 변경되는 경우, 페이지로 돌아올 때까지 기다리기 원할 수 있습니다.)

유저 에이전트들은 특히 사용자가 뷰포트의 크기를 변경하는 경우 (예를 들어 윈도우를 리사이징하거나 페이지 줌을 변경하여), 그리고 img 요소(element)가 문서에 삽입되는 경우, 이 알고리즘이 수행되도록 권장되기 때문에, 밀도 보정 고유 너비와 높이는 새로운 뷰포트에 일치하고, 때문에 art direction이 수반되는 경우 올바른 이미지가 선택됩니다.

  1. 병렬로 안정 상태를 기다립니다. 동기 섹션은 알고리즘이 동기 섹션이 종료되었다고 알리기 전까지 이 알고리즘의 모든 나머지 단계들로 구성됩니다. (동기 섹션의 단계들은 ⌛로 표기 됩니다.)
  2. img 요소(element)가 srcsetpicture를 사용하지 않거나, 그것의 노드 문서활성 문서가 아니거나, 리소스 유형이 multipart/x-mixed-replace인 이미지 데이터를 가지거나, 보류 중인 요청이 null이 아니라면, 이 알고리즘을 중단합니다.
  3. selected sourceselected pixel density를 각각 URL과 이미지 소스 선택의 결과 픽셀 밀도로 둡니다.
  4. selected source가 null이라면, 이 단계들을 중단합니다.
  5. selected sourceselected pixel density가 요소(element)의 마지막 선택된 소스현재 픽셀 밀도와 동일하다면, 이 단계들을 중단합니다.
  6. selected source해석하고, 요소(element)의 노드 문서에 관련 짓고, absolute URL결과 URL 문자열로 둡니다. 그것이 성공적이지 않다면, 이 단계들을 중단합니다.
  7. corsAttributeState를 요소(element)의 crossorigin 콘텐트 속성(attriute)의 상태로 둡니다.
  8. originimg 요소(element)의 노드 문서출처(origin)로 둡니다.
  9. clientimg 요소(element)의 노드 문서Window 객체의 환경 설정 객체로 둡니다.
  10. ⌛ Let keyabsolute URLcorsAttributeState와, corsAttributeStateNo CORS라면 origin으로 구성되는 튜플로 둡니다.
  11. image request현재 URLabsolute URL인 새로운 이미지 요청으로 둡니다.
  12. ⌛ 요소의 보류 중인 요청이미지 요청으로 둡니다.
  13. 병렬로 나머지 단계들을 계속하여, 동기 섹션을 종료합니다.
  14. 사용 가능한 이미지들의 목록key에 대한 항목을 포함한다면, image request이미지 데이터를 항목의 그것으로 설정합니다. 다음 단계로 계속합니다.

    그렇지 않으면, 이 하위 단계들을 수행합니다:

    1. requestabsolute URLcorsAttributeState이 주어진 잠정적 CORS 요청을 생성한 결과로 둡니다.
    2. request클라이언트client로, 유형을 "image"로 설정하고, request동기 플래그를 설정합니다.
    3. responserequest가져온(fetch) 결과로 둡니다.
    4. response의 안전하지 않은 응답이 네트워크 오류이거나, (앞서 언급된 것 처럼, 이미지 스니핑 규칙들을 적용하여 결정된) 이미지 형식이 지원되지 않거나, 유저 에이전트가 image request의 이미지가 치명적인 방법으로 이미지 치수들을 얻을 수 없는 오류가 생겼다고 결정할 수 있거나, 리소스 유형이 multipart/x-mixed-replace라면, 보류 중인 요청을 null로 두고 이 단계들을 중단합니다.
    5. 그렇지 않으면, response의 안전하지 않은 응답은 image request이미지 데이터입니다. 이것은 CORS-동일-출처CORS 교차 출처일 수 있습니다; 이것은 아미지 자체의 출처(origin)에 영향을 줍니다 (예를 들어, canvas에 사용되는 경우).
  15. 다음 하위 단계들을 수해행하기 위한 작업을 대기열에 넣습니다:

    1. img 요소(element)가 이 알고리즘이 시작된 이후 관련 변경들 경험이 있다면, 보류 중인 요청을 null로 두고 이 단계들을 중단합니다.
    2. img 요소(element)의 마지막 선택된 소스selected source로 그리고 img 요소(element)의 현재 픽셀 밀도selected pixel density로 둡니다.
    3. image request완전히 사용 가능 상태로 설정합니다.
    4. key를 사용하여, 상위 계층 캐싱 무시 플래그 설정을 가지고 이미지를 사용 가능한 이미지들의 목록에 추가(add) 합니다.
    5. 지연 요청을 현재 요청으로 업그레이드 합니다.
    6. img 요소(element)의 표현을 적절하게 업데이트 합니다.
    7. img 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시킵니다.

이 섹션내 알고리즘에 의해 대기열에 넣어진 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.


img 요소(element)가 나타내는 것은 src 속성(attribute)과 alt 속성(attribute)에 따라 달라집니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 빈 문자열로 설정되었다면

이미지는 콘텐트의 나머지에 대해 문서 내 일부 다른 정보와 중복되는 장식적이거나 보조적인 것입니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표현하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다.

그렇지 않으면, 요소(element)는 아무 것도 나타내지 않고, 렌더링으로부터 완전히 생략될 것입니다. 유저 에이전트들은 이미지가 존재하지만 렌더링으로부터 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 비어 있지 않은 값으로 설정되었다면

이미지는 콘텐트의 중요한 부분입니다; alt 속성(attribute)은 이미지에 대한 텍스트 형식의 동등한 것이나 대체를 제공합니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표시하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다 .

그렇지 않으면, 요소(element)는 alt 속성(attribute)에 의해 주어진 텍스트를 나타냅니다. 유저 에이전트들은 이미지가 존재하지만 렌더링으로부터 생략되었다는 알림을 사용자에게 제공할 수 있습니다.

src 속성(attribute)이 설정되었고 alt 속성(attribute)이 설정되지 않았다면

사용 가능한 이미지의 텍스트 형식의 동등한 것이 존재하지 않습니다.

이미지가 사용 가능하고 유저 에이전트가 그 이미지를 표시하도록 설정되었다면, 요소(element)는 요소(element)의 이미지 데이터를 나타냅니다.

그렇지 않으면, 유저 에이전트는 렝더링 되지 않는 이미지가 있음을 나타내는 일종의 지시기를 표시해야(should) 하고, 사용자에 의해 요청되었거나 그렇게 설정되었거나, 탐색에 대한 응답으로 상황에 맞는 정보를 제공하도록 요구된 경우 다음과 같이 얻어진 이미지에 대한 캡션 정보를 제공할 수 있습니다:

  1. 이미지가 자식 figcaption 요소(element)를 가진 figure 요소(element)의 후손이고, figcaption 요소(element)와 그것의 후손을 무시하고 figure 요소(element)가 요소(element) 간 여백 외 다른 후손 Text 노드를 가지지 않고, img 요소(element) 외 후손 삽입(embedded) 콘텐트가 없다면, 첫 번째 그 figcaption 요소(element)의 콘텐츠가 캡션 정보입니다; 이 단계들을 중단합니다.
  2. 캡션 정보가 존재하지 않습니다.
src 속성(attribute)이 설정되지 않았거나, alt 속성(attribute)이 빈 문자열로 설정되었거나 alt 속성(attribute)이 전혀 설정되지 않았다면

요소(element)는 아무 것도 나타내지 않습니다.

그렇지 않으면

요소(element)는 alt 속성(attribute)에 의해 주어진 텍스트를 나타냅니다.

alt 속성(attribute)은 조언 정보를 나타내지 않습니다. 유저 에이전트들은 title 속성(attribute)의 콘텐트와 동일한 방식으로 alt 속성(attribute)의 콘텐츠를 표현하지 않아야(must) 합니다.

유저 에이전트들은 사용자에게 이미지를 표시하거나, 이미지가 표시되는 것을 막는 옵션을 옵션을 항상 제공할 수 있습니다. 유저 에이전트들은 또한 사용자가 그것을 볼 수 없을 경우, 예를 들어, 시각 장애 때문에 혹은 그들이 그래픽 기능이 없는 텍스트 단말기를 사용하기 때문에, 이미지를 사용할 수 있도록 휴리스틱을 적용할 수 있습니다. 그러한 휴리스틱들은 예를 들어, 이미지 내에서 발견된 텍스트의 광학 문자 인식 (OCR)을 포함할 수 있습니다.

유저 에이전트들이 alt 속성(attribute)들이 누락되는 케이스를 바로잡도록 권장되는 반면, 작성자들은 그러한 행위에 의존하지 않아야(must) 합니다. 이미지들에 대한 대체로서 수행하도록 텍스트를 제공하는 요구사항들은 아래 상세 내용에 기술됩니다.

img 요소(element)들의 콘텐츠가 있다면, 렌더링 목적을 위해 무시됩니다.


usemap 속성(attribute)이 존재한다면 이것은 이미지가 연관된 이미지 맵을 가진다는 것을 나타낼 수 있습니다.

ismap 속성(attribute)은, href 속성(attribute)을 가진 a 요소(element)의 후손인 요소(element)에 사용되는 경우, 그것의 존재로 인해 요소(element)가 서버측 이미지 맵에 대한 접근을 제공한다는 나타냅니다. 이것은 이벤트들이 해당하는 a 요소(element)에 처리되는 방법에 영향을 줍니다.

ismap 속성(attribute)은 불리언 속성(attribute)입니다. 속성(attribute)은 href 속성(attribute)를 가진 조상 a 요소(element)를 가지지 않는 요소(element)에 명시되지 않아야(must) 합니다.

usemapismap 속성(attribute)들은 picture 요소(element)에 명시된 media 속성(attribute)을 가진 source 요소(element)와 함께 사용되는 경우 혼란스러운 행동을 가져올 수 있습니다.

img 요소(element)는 치수 속성(attribute)들을 지원합니다.

alt, src, srcset, sizes IDL 속성(attribute)들은 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

crossOrigin IDL 속성(attribute)은 crossorigin 콘텐트 속성(attribute)을 반영해야(must) 합니다.

useMap IDL 속성(attribute)은 usemap 콘텐트 속성(attribute)을 반영해야(must) 합니다.

isMap IDL 속성(attribute)은 ismap 콘텐트 속성(attribute)을 반영해야(must) 합니다.

image . width [ = value ]
image . height [ = value ]

이 속성(attribute)들은 이미지의 실제 렌더링 된 치수들이나 치수를 알 수 없다면 0을 반환합니다.

그것들은 해당하는 콘텐트 속성(attribute)들을 변경하기 위해 설정 될 수 있습니다.

image . naturalWidth
image . naturalHeight

이 속성(attribute)들은 이미지의 고유 치수들이나 치수를 알 수 없다면 0을 반환합니다.

image . complete

이미지가 완전히 다운로드 되었거나 이미지가 명시되지 않았다면 true를 반환합니다; 그렇지 않으면 false를 반환합니다.

image . currentSrc

이미지의 절대 URL을 반환합니다.

image = new Image( [ width [, height ] ] )

관련된 인수로 전달된 값이 사용 가능하다면 그 값으로 설정된 widthheight 속성(attribute)를 가진 새로운 img 요소(element)를 반환합니다.

IDL 속성(attribute) widthheight는 이미지가 렌더링 되고 있고 시각 매체에 렌더링 되고 있다면 CSS 픽셀로 이미지의 렌더링 된 너비와 높이를 반환해야(must) 하거나; 이미지가 고유 치수들을 가지고 사용 가능 하지만 시각 매체에 렌더링 되고 있지 않다면 이미지의 밀도 보정 고유 너비와 높이를 CSS 픽셀로 반환해야(must) 하거나; 이미지가 사용 가능 하지않거나 고유 치수들을 가지지 않는다면 0을 반환해야(must) 합니다. [CSS-2015]

설정할 때, 그것들은 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영한 것처럼 수행해야(must) 합니다.

IDL 속성(attribute)들 naturalWidthnaturalHeight는 이미지가 고유 치수들을 가지고 사용 가능 하다면 이미지의 밀도 보정 고유 너비와 높이를 CSS 픽셀로 반환해야(must) 하고, 그렇지 않으면 0을 반환해야(must) 합니다. [CSS-2015]

IDL 속성(attribue) complete는 다음 조건 중 어떤 것이라도 참이라면 true를 반환해야(must) 합니다:

그렇지 않으면, 속성(attribute)은 false를 반환해야(must) 합니다.

complete의 값은 따라서 script가 실행되는 동안 변경될 수 있습니다.

currentSrc IDL 속성(attribute)은 img 요소(element)의 현재 요청현재 URL을 반환해야(must) 합니다.

생성자는 HTMLImageElement 객체를 (이외에도 createElement() 같은 DOM에서 팩토리 메서드) 생성하기 위해 제공됩니다: Image(width, height). 생성자가 호출 될 때, 이것은 새로운 HTMLImageElement 객체를 (새로운 img 요소(element)를) 반환해야(must) 합니다. width 인자가 존재한다면, 새로운 객체의 width 콘텐트 속성(attribute)은 width로 설정되어야(must) 합니다. height 인자 역시 존재한다면, 새로운 객체의 height 콘텐트 속성(attribute)은 height로 설정되어야(must) 합니다. 요소(element)의 노드 문서는 호출된 생성자의 인터페이스 객체가 발견된 Window 객체의 브라우징 컨텍스트활성 문서이어야(must) 합니다.

4.7.5.1. 이미지에 대한 대체로 수행하기 위한 텍스트 제공에 대한 요구사항들

대체 텍스트는, [WCAG20], 사용자의 요구들에 해당하는 많은 감각 양식들을 (예를 들어, 시각, 오디오, 촉각) 통해 렌더링될 수 있기 때문에, 시각 정보를 접근 가능하게 만드는 주요한 방법입니다. 대체 텍스트를 제공하는 것은 정보가 다양한 유저 에이전트들에 의한 다양한 방법으로 렌더링되는 것을 허용합니다. 예를 들어, 그림을 볼 수 없는 사람은 음성 합성을 사용하여 대체 텍스트를 크게 읽는 것을 들을 수 있습니다.

이미지의 alt 속성(attribute)은 매우 중요한 접근성 속성(attribute)입니다. 유용한 alt 속성(attribute) 콘텐트를 작성하는 것은 작성자가 이미지가 나타나는 컨텍스트와 그 컨텍스트에서 이미지가 가질 수 있는 기능을 신중하게 고려할 것이 요구됩니다.

여기에 포함된 지침은 작성자들이 이미지들을 사용하는 가장 일반적인 방법을 다룹니다. 추가적인 지침과 기법들은 이미지들에 대한 대체 텍스트의 리소스들에 사용 가능합니다.

4.7.5.1.1. 이미지들에 대한 대체 텍스트들로부터 사용자가 이익을 얻는 시나리오의 예
4.7.5.1.2. 일반 지침들

달리 명시된 경우를 제외하고, alt 속성(attribute)는 명시되어야(must) 하고 그것의 값은 비어있지 않아야(must) 합니다; 값은 이미지에 대해 적절한 기능적인 대체여야(must) 합니다. alt 속성(attribute) 콘텐트에 대한 특정한 요구사항들은 아래 섹션들에 기술된 대로, 페이지 내에서 이미지의 기능에 달려 있습니다.

적절한 대체 텍스트를 결정하기 위해서는 이미지가 페이지에 포함되는 이유에 대해서 생각하는 것이 중요합니다. 그 목적이 무엇인가? 이 처럼 생각하는 것이 의도된 대상을 위해 이미지에 관하여 무엇이 중요한지를 이해하는 것을 도울 것입니다. 모든 이미지들은 유용한 정보를 제공하거나, 기능을 수행하거나, 상호작용 요소(element)에 레이블을 달거나, 심미적 향상이나 순수하게 장식이기 때문에, 페이지에 존재하는 이유를 가집니다. 그러므로, 이미지가 무엇을 위한 것인지를 아는 것은, 더 쉽게 적절한 대체 텍스트를 작성하게 합니다.

하이퍼링크a 요소(element)나 button 요소(element)가 텍스트 콘텐트를 가지지 않고 하나 이상의 이미지들만을 포함하는 경우, 모두 링크나 버튼의 목적을 전달하는 alt 속성(attribute)들 내에 텍스트를 포함합니다.

이 예에서, 작성 인터페이스의 일부가 표시됩니다. 각 버튼은 사용자가 편집 중인 콘텐트를 취할 수 있는 동작을 나타내는 아이콘을 가집니다. 이미지들을 볼 수 없는 사용자들을 위해, 동작 이름들이 이미지들의 alt 속성(attribute)들 내에 포함됩니다.

5개의 버튼들: 굵게, 기울임, 취소선, 글머리 기호 목록과 숫자 목록.

<ul>
  <li><button><img src="b.png" alt="Bold"></button></li>
  <li><button><img src="i.png" alt="Italics"></button></li>
  <li><button><img src="strike.png" alt="Strike through"></button></li>
  <li><button><img src="blist.png" alt="Bulleted list"></button></li>
  <li><button><img src="nlist.png" alt="Numbered list"></button></li>
</ul>
이 예에서, 링크는 로고를 포함합니다. 링크는 외부 사이트로부터 W3C 웹 사이트를 가리킵니다. 대체 텍스트는 링크 대상에 대한 간략한 설명입니다.

링크 콘텐트로 사용된 W3C 로고

<a href="https://w3.org">
<img src="images/w3c_home.png" width="72" height="48" alt="W3C web site">
</a>
이 예는 링크가 W3C 웹 사이트에 있는 것을 제외하고 이전 예와 동일합니다. 대체 텍스트는 링크 대상에 대한 간략한 설명입니다.

링크 콘텐트로 사용된 W3C 로고

<a href="https://w3.org">
<img src="images/w3c_home.png" width="72" height="48" alt="W3C home">
</a>

로고의 이미지가 사용되는 상황에 따라 대체 텍스트의 일부로, 이미지가 로고라는 표시를 제공하는 것은 적절할 수 있습니다. 섹션 §4.7.5.1.19 로고, 휘장, 깃발, 엠블럼를 참조하세요.

이 예에서, 링크는 인쇄 미리보기 아이콘을 퐇마합니다. 링크는 적용된 인쇄 스타일시트를 가진 페이지의 버전을 가리킵니다. 대체 텍스트는 링크 대상에 대한 간단한 설명 입니다.

링크 콘텐트로 사용된 인쇄 미리보기 아이콘.

<a href="preview.html">
<img src="images/preview.png" width="32" height="30" alt="Print preview.">
</a>
이 예에서, 버튼은 검색 아이콘을 포함합니다. 버튼은 검색 양식을 전송합니다. 대체 텍스트는 버튼이 무엇을 하는지에 대한 간단한 설명입니다.

버튼 콘텐트로 사용된 검색 아이콘.

<button>
<img src="images/search.png" width="74" height="29" alt="Search">
</button>
이 예에서, PIP Corporation에 대한 회사 로고는 다음 두 개의 이미지들로 분리되고, 첫 번째 것은 단어 PIP를 포함하고 두 번째 것은 축약된 단어 CO를 가집니다. 이미지들은 PIPCO 홈페이지로의 링크의 단독 콘텐트 입니다. 이 경우 링크 대상에 대한 간단한 설명이 제공됩니다. 이미지들은 사용자에게 단일 항목으로 표현되기 대문에 대체 텍스트 PIP CO home이 첫 번째 이미지의 alt 내에 있습니다.

텍스트 'PIP'를 포함하는 이미지.텍스트 'CO'를 포함하는 이미지.

<a href="pipco-home.html">
<img src="pip.gif" alt="PIP CO home"><img src="co.gif" alt="">
</a>
4.7.5.1.4. 그래픽 표현: 차트, 도표, 그래프, 지도, 일러스트

사용자들은 콘텐트가 그래픽 형식, 예를 들어, 흐름도, 도표, 그래프, 방향들을 보여주는 지도로 표현되는 경우 유용할 수 있습니다. 이미지를 볼 수 없는 사용자들 역시 그래픽 형식으로 표현된 콘텐트가 텍스트 기반 형식으로 제공되는 경우 유용할 수 있습니다. 텍스트 콘텐트를 처리하지만 이미지들을 자동으로 처리할 수 없는 소프트웨어 에이전트들 (예를 들어, 번역 서비스들, 많은 검색 엔진들) 역시 텍스트 기반 설명으로부터 이점을 얻을 수 있습니다.

다음 예에 원형 차트 내에 보여진 데이터를 나타내는 alt 속성(attribute) 내에 텍스트를 가진 원형 차트의 이미지가 있습니다:

Browser Share: Internet Explorer 25%, Firefox 40%, Chrome 25%, Safari 6% and Opera 4%.

<img src="piechart.gif" alt="Pie chart: Browser Share - Internet Explorer 25%, Firefox 40%, Chrome 25%, Safari 6% and Opera 4%.">
이미지의 경우 그래픽 형식으로 이전 문단을 반복합니다. alt 속성(attribute) 콘텐트는 이미지를 라벨링 합니다.
<p id="graph7">According to a recent study Firefox has a 40% browser share,
  Internet Explorer has 25%, Chrome has 25%, Safari has 6% and Opera has 4%.</p>
<p><img src="piechart.gif" alt="The browser shares as a pie chart."></p>

이미지가 사용 불가능한 경우, 예를 들어 src 속성(attribute) 값이 부정확한 경우, 대체 텍스트가 사용자에게 이미지 콘텐트의 간단한 설명을 제공하는 것을 볼 수 있습니다:

위 코드 조각의 표현.

한 문장이나 두 문장 이상으로 대체 텍스트가 긴 경우나 혹은 구조적 마크업의 사용으로 이점을 얻는 경우, alt 속성(attribute)과 연관된 대체 텍스트를 사용하여 간단한 설명을 제공하거나 라벨을 답니다.

여기 alt 속성(attribute)에 포함된 짧은 대체 텍스트를 가진 흐름도 이미지의 예가 있고, 이 경우 대체 텍스트는 이미지가 링크의 단독 콘텐트로서 링크 대상에 대한 설명입니다. 링크는 동일한 문서 내에서 흐름도에서 표현된 처리의 설명을 가리킵니다.

흐름도: 고장난 램프 다루기.

<a href="#desc"><img src="flowchart.gif"
  alt="Flowchart: Dealing with a broken lamp."></a>

...

...

<div id="desc">
<h2>Dealing with a broken lamp</h2>
<ol>
<li>Check if it’s plugged in, if not, plug it in.</li>
<li>If it still doesn’t work; check if the bulb is burned out. If it is, replace the bulb.</li>
<li>If it still doesn’t work; buy a new lamp.</li>
</ol>
</div>
이 예에 차트 이미지가 있습니다. 정보가 데이터 집합이기 때문에 alt 속성(attribute) 내에 있는 평문 텍스트로서 차트 내에 그려진 정보를 제공하는 것은 적절하지 않을 것입니다. 대신 구조화된 대체 텍스트가 아래 이미지를 차트 이미지에 표현된 데이터를 사용하여 데이터 테이블의 형태로 제공됩니다.

막대 차트: 국가와 계절에 따른 강우량 평균. 전체 설명은 아래 테이블에 있습니다.

각 계절에 대한 최고와 최저 강우량의 표시자들은 표에 포함되었기 때문에, 차트 내에 쉽게 식별된 추세 역시 데이터 테이블에서도 사용 가능합니다.

국가와 계절에 따른 평균 강우량(mm).
영국 일본 오스트리아
5.3 (최고) 2.4 2 (최저)
여름 4.5 (최고) 3.4 2 (최저)
가을 3.5 (최고) 1.8 1.5 (최저)
겨울 1.5 (최고) 1.2 1 (최저)
<figure>
<figcaption>Rainfall Data</figcaption>
<img src="rainchart.gif" alt="Bar chart: average rainfall by Country and Season.
Full description in Table below.">
<table id="table-4">
<caption>Rainfall in millimetres by Country and Season.</caption>
<tr><td><th scope="col">UK <th scope="col">Japan<th scope="col">Australia</tr>
<tr><th scope="row">Spring <td>5.5 (highest)<td>2.4 <td>2 (lowest)</tr>
<tr><th scope="row">Summer <td>4.5 (highest)<td>3.4<td>2 (lowest)</tr>
<tr><th scope="row">Autumn <td>3.5 (highest) <td>1.8 <td>1.5 (lowest)</tr>
<tr><th scope="row">Winter <td>1.5 (highest) <td>1.2 <td>1 lowest</tr>
</table>
</figure>

figure 요소(element)는 막대 차트 이미지와 데이터 테이블을 그룹핑 하는데 사용됩니다. figcaption 요소(element)는 그룹화 된 콘텐트에 대한 캡션을 제공합니다.

이 섹션의 모든 예제에 대해 이미지들에 대한 텍스트 설명들이 필요할 때만 표시되도록 detailssummary 요소(element)가 사용될 수 있습니다:

닫힘 상태의 details 요소(element).

표시된 목록 콘텐트들을 가진 열림 상태의 details 요소(element).

<figure>
<img src="flowchart.gif" alt="Flowchart: Dealing with a broken lamp.">
<details>
<summary>Dealing with a broken lamp</summary>
<ol>
<li>Check if it’s plugged in, if not, plug it in.</li>
<li>If it still doesn’t work; check if the bulb is burned out. If it is, replace the bulb.</li>
<li>If it still doesn’t work; buy a new lamp.</li>
</ol>
</details>
</figure>

details and summary 요소(element)들은 현재 브라우저들에서 잘 지원되지 않기 때문에, 사용된다면 그것들이 지원될 때까지는 기능적으로 제공하기 위해 스크립팅을 사용해야 할 필요가 있을 것입니다. 비슷한 기능을 제공하는 대중적인 자바스크립트 UI 위젯 라이브러리들에 사용자 정의 컨트롤들이 사용 가능한 스크립팅 된 폴리필(polyfill)들이 많이 있습니다.

4.7.5.1.5. 텍스트 이미지들

때때로, 이미지는 텍스트만을 포함하고, 이미지의 목적은 시각적 효과와/혹은 글꼴을 사용하여 텍스트를 나타내는 것입니다. CSS를 사용하여 꾸며진 텍스트가 사용되도록 강력하게 권장되지만, 그것이 불가능하다면, 이미지에 있는 것과 같은 alt 속성(attribute)에 동일한 텍스트를 제공합니다.

이 예는 화려한 여러 색상의 손으로 그린 스타일로 쓰여진 텍스트 "Get Happy!"의 이미지를 보여줍니다. 이미지는 제목(heading)의 콘텐트를 구성합니다. 이 예에서 이미지에 대한 대체 텍스트는 "Get Happy!"입니다.

Get Happy!

<h1><img src="gethappy.gif" alt="Get Happy!"></h1>
이 예에는 텍스트로 구성된 광고 이미지가 있이며, 문구 "The BIG sale"이 3번 반복되고, 각 반목마다 텍스트는 작아지고 희미해지며, 마지막 줄은 "...ends Friday"라고 읽힙니다. 광고로서 사용되는 상황에서 이미지의 대체 텍스트는 반복은 시각적 효과를 위한 것이고 텍스트의 반복은 이미지를 볼 수 없는 사람들에 대해 불필요하고 혼란스러울 수 있기 때문에 텍스트 "The BIG sale"만을 포함하도록 권장됩니다.

The big sale ...ends Friday.

<p><img src="sale.gif" alt="The BIG sale ...ends Friday."></p>

텍스트 이미지와 함께 사진이나 다른 그래픽이 존재하는 상황에서, 이미지 텍스트 내의 단어들이 이미지를 볼 수 있는 사용자들에게 의미(meaning)를 전달하는 이미지의 다른 설명과 함께, 정보가 이미지를 볼 수 없는 사용자에게도 사용 가능하도록 대체 텍스트로 포함되는 것을 보장하세요.

이미지가 유니코드로 달리 표현될 수 없는 문자를 표현하는데 사용되는 경우, 예를 들어 가이지(がいじ, 外字), 이타이지(いたいじ, 異体字), 새로운 통화 표시 같은 새로운 문자, 대체 텍스트는 동일한 것을 작성하는 종래의 방법이 되어야 합니다, 예를 들어 문자의 발음을 제공하는 음성기호 히라가라나 카타카나를 사용하여.
1997년의 이 예에서, 중앙에 한 개 대신 두 개의 바가 있는 동그랗게 말린 E 같이 보이는 최신식 통화 기호가 이미지를 사용하여 표현됩니다. 대체 텍스트는 문자의 발음을 제공합니다.

Only euro 5.99!

<p>Only <img src="euro.png" alt="euro ">5.99!

유니코드 문자가 동일한 목적으로 제공한다면 이미지는 사용되지 않아야(should) 합니다. 유니코드를 사용하여 직접적으로 텍스트가 표현될 수 없을 경우에만, 예를 들어 장식이거나 문자가 유니코드 문자 세트에 없기 때문인 경우 (가이지의 경우처럼), 이미지가 적절할 것입니다.

기본 시스템 글꼴이 제공된 문자를 지원하지 않기 때문에 작성자가 이미지를 사용하도록 유인된다면, 이미지들 보다는 웹 폰트들이 더 나은 해결책입니다.

채색을 한 원고는 그것의 문자들에 대해 그래픽을 사용할 수 있습니다. 그러한 상황에서 대체 텍스트는 단지 이미지가 나타내는 문자입니다. Once upon a time and a long long time ago...
<p><img src="initials/fancyO.png" alt="O">nce upon a time and a long long time ago...
4.7.5.1.6. 텍스트를 포함하는 이미지들

종종, 이미지는 차트와 같은 그래픽과 연관된 텍스트로 구성됩니다. 이 경우 이미지 내 텍스트는 대체 텍스트에 포함되도록 권장됩니다.

원형 차트와 관련된 텍스트를 포함하는 이미지를 고려해보세요. 관련된 텍스트를 가능한 이미지 텍스트가 아니라 텍스트로서 제공하는 것이 권장됩니다. 이것이 불가능하다면 이미지로 전달되는 적절한 정보와 함께 대체 텍스트에 텍스트를 포함시키세요.

Figure 1. Distribution of Articles by Journal
  Category. Pie chart: Language=68%, Education=14% and Science=18%.

<p><img src="figure1.gif" alt="Figure 1. Distribution of Articles by Journal Category.
Pie chart: Language=68%, Education=14% and Science=18%."></p>
여기 alt 속성(attribute)에 포함된 짧은 텍스트와 텍스트로 긴 대체 텍스트를 보여주는, 동일한 원형 차트 이미지의 다른 예가 있습니다. figurefigcaption 요소(element)들이 이미지와 연관된 긴 대체 텍스트로 사용됩니다. alt 속성(attribute)은 이미지를 라벨링 하는데 사용됩니다.
<figure>
<img src="figure1.gif" alt="Figure 1">
<figcaption><strong>Figure 1.</strong> Distribution of Articles by Journal Category.
Pie chart: Language=68%, Education=14% and Science=18%.</figcaption>
</figure>

이전 예보다 이 방법이 유리한 것은 대체 텍스트가 항상 모든 사용자에게 사용 가능하다는 것입니다. alt 속성(attribute)을 사용하여 제공되는 대체 텍스트는 구조화 된 마크업을 허용되지 않는 반면, 이것은 또한 구조화 된 마크업이 대체 텍스트에 사용되는 것을 허용합니다.

4.7.5.1.7. 페이지 콘텐트의 테마나 주제를 향상시키는 이미지

주변 텍스트에 의해 직접적으로 논의되지 않지만 여전히 어떤 관련성을 가지는 이미지가 img 요소(element)를 사용하여 페이지에 포함될 수 있습니다. 그러한 이미지들은 단순한 장식 이상이고, 페이지의 테마나 주제를 증대시킬 수 있고 때문에 여전히 콘텐트의 일부를 형성합니다. 이러한 경우, 대체 텍스트가 제공되도록 권장됩니다.

페이지 콘텐트의 주제와 밀접하게 관련되지만 직접적으로 논의되지 않는 이미지의 예가 여기 있습니다. 시를 낭송하는 페이지에, 그림 이미지는 시에 의해 영감을 받았습니다. 다음 코드 조각은 예를 보여줍니다. 이미지는 "샬롯의 부인"이라는 제목의 그림이고, 그것은 시에서 영감을 받았고 그것의 주제는 시로부터 유래됩니다. 따러서 대체 텍스트가 제공되도록 강력히 권장됩니다. alt 속성(attribute) 내에 이미지의 콘텐트의 짧은 설명과 문서의 하단에 위치한 긴 설명으로의 링크가 이미지 아래에 있습니다. 긴 설명의 끝에 그림에 대한 더 자세한 정보로의 링크도 있습니다.

A painting inspired by Alfred Tennyson’s poem The Lady of Shalott

<header>
<h1>The Lady of Shalott</h1>
<p>A poem by Alfred Lord Tennyson</p>
</header>

<img src="shalott.jpeg" alt="Painting - a young woman with long hair, sitting in a wooden boat. Full description below.">
<p><a href="#des">Description of the painting</a>.</p>

<!-- Full Recitation of Alfred, Lord Tennyson’s Poem.  -->

...
...
...
<p id="des">The woman in the painting is wearing a flowing white dress. A large piece of intricately
patterned fabric is draped over the side. In her right hand she holds the chain mooring the boat. Her expression
is mournful. She stares at a crucifix lying in front of her. Beside it are three candles. Two have blown out.
<a href="https://bit.ly/5HJvVZ">Further information about the painting</a>.</p>

이 예는 페이지의 주요 주제의 사진으로서 이미지를 식별하는 대체 텍스트의 제공을 보여줍니다.

Portrait photo(black and white) of Robin, accompanied by a heading 'Robin Berjon' and a question
  'what more needs to be said?'

<img src="orateur_robin_berjon.png" alt="Portrait photo(black and white) of Robin.">
<h1>Robin Berjon</h1>
<p>What more needs to be said?</p>
4.7.5.1.8. 주변 텍스트의 일부의 그래픽 표현

많은 경우, 이미지는 실제로 단지 부수적일 뿐이고, 그것의 존재는 단순히 주변 텍스트를 보충합니다. 이러한 경우, alt 속성(attribute)는 존재해야 하지만 그 값은 빈 문자열이어야(must) 합니다.

일반적으로, 이미지를 삭제하는 것이 페이지를 전혀 덜 유용하게 만들지 않는다면 이 카테고리로 분류되지만, 이미지를 포함하는 것은 그것을 시각 브라우저들의 사용자에 대해 개념을 이해시키는데 많은 부분 쉽게 만듭니다.

이미지에 대한 유용한 대체 텍스트를 작성하는 것은 항상 쉬운 일은 아니며, 다른 옵션은 가능하다면 이미지에 대한 설명이나 더 상세한 정보로의 링크를 제공하는 것입니다. 동일한 이미지의 이 예에, alt 속성(attribute) 내에 포함된 짧은 대체 텍스트가 있고, 이미지 이후에 링크가 있습니다. 링크는 그림에 대한 정보를 포함하는 페이지를 가리킵니다.

The Lady of Shalott

A poem by Alfred Lord Tennyson.

Painting of a woman in a white flowing dress, sitting in a small boat.

About this painting

Full recitation of Alfred, Lord Tennyson’s poem.

<header><h1>The Lady of Shalott</h1>
<p>A poem by Alfred Lord Tennyson</p></header>
<figure>
<img src="shalott.jpeg" alt="Painting: a woman in a white flowing dress, sitting in a small boat.">
<p><a href="https://bit.ly/5HJvVZ">About this painting.</a></p>
</figure>
<!-- Full Recitation of Alfred, Lord Tennyson’s Poem.  -->
4.7.5.1.9. 어떤 정보도 추가하지 않는 순수한 장식 이미지

순수하게 장식적인 이미지들은 이미지들을 볼 수 있는 사람들에 대한 미학을 넘어선 기능이나 정보를 제공하지 않는 시각적 향상 이나 장식 혹은 꾸밈들입니다.

순수하게 장식적인 이미지들이 보조 기술에 의해 무시 될 수 있도록 빈 alt 속성(attribute)을 (alt="") 사용하여 마크업 하세요. 장식적인 이미지들을 인라인에 포함시키는 것은 용인할 수 없는 것이 아니지만, 그것들이 순수하게 장식적인 경우 CSS를 사용하여 이미지를 포함하는 것이 권장됩니다.

개인의 블로그에 대한 장식 배너로서 사용되는 이미지의 예가 여기 있습니다. 이 이미지는 어떠한 정보도 제공하지 않고 따라서 빈 alt 속성이 사용됩니다.

Clara’s Blog Welcome to my blog...

<header>
<div><img src="border.gif" alt="" width="400" height="30"></div>
<h1>Clara’s Blog</h1>
</header>
<p>Welcome to my blog...</p>
4.7.5.1.10. 인라인 이미지들

이미지들이 문장에서 텍스트의 흐름의 일부로 인라인으로 사용되는 경우, 떨어진 문장의 맥락에서 의미가 통하는 대체 텍스트로서 단어나 구문을 제공하세요.

I love you.
I <img src="heart.png" alt="love"> you.

My heart breaks.

My <img src="heart.png" alt="heart"> breaks.

그림이 나중에 다시 온전한 그림을 형성하도록 함께 표시되는 작은 이미지 파일들로 잘려진 경우, 전체로서 그림에 대한 관련 지침에 따라 alt 속성(attribute)을 사용하여 이미지들 중 하나에 대체 텍스트를 포함시키고, 이후 다른 이미지들에는 빈 alt 속성(attribute)을 포함시키세요.

이 예에서, PIP Corporation에 대한 회사 로고를 나타내는 그림이 두 개 조각, 글자 "PIP"를 포함하는 첫 번째와 단어 "CO"를 가진 두 번째로 분할되었습니다. 대체 텍스트 PIP CO는 첫 번째 이미지의 alt 속성(attribute)에 있습니다.

Image containing the text 'PIP'.Image containing the text 'CO'.

<img src="pip.gif" alt="PIP CO"><img src="co.gif" alt="">
다음 예에서, 비율이 세 개의 채워진 별과 두 개의 빈 별로 보여집니다. 대체 테스트는 "★★★☆☆"일 수 있지만, 작성자는 대신 "3 out of 5"의 형식으로 좀 더 유용하게 순위를 제공하기록 결정했습니다. 그것은 첫 번째 이미지의 대체 텍스트이고, 나머지는 빈 alt 속성(attribute)들을 가집니다. 3 out of 5.
<p>Rating:
<img src="1" alt="3 out of 5">
<img src="1" alt=""><img src="1" alt="">
<img src="0" alt=""><img src="0" alt="">
</p>
4.7.5.1.12. 이미지 지도
img 요소(element)가 href 속성(attribute)들을 가지는 area 요소(element)들을 포함하는 map 요소(element)를 참조하는 usemap 속성(attribute)을 가진다면, img는 상호 작용 콘텐트로 간주됩니다. 그러한 경우, alt 속성(attribute)을 사용하여 항상 이미지에 대한 대체 텍스트를 제공하세요.

카툼바의 지도인 다음 이미지를 고려해보세요, 그것은 북과 남 카툼바의 영역에 해당하는 두 상호 작용 영역을 가집니다:

Map of Katoomba.

North Katoomba South Katoomba 대체 텍스트는 이미지에 대한 간단한 설명입니다. area 요소(element)들의 각각의 alt 속성(attribute)은 각 링크된 영역의 대상 페이지의 콘텐트를 설명하는 텍스트가 제공됩니다:
<p>View houses for sale in North Katoomba or South Katoomba:</p>
  <p><img src="imagemap.png" width="209" alt="Map of Katoomba" height="249" usemap="#Map">

  <map name="Map">
  <area shape="poly" coords="78,124,124,10,189,29,173,93,168,132,136,151,110,130"
  href="north.html" alt="Houses in North Katoomba">
  <area shape="poly" coords="66,63,80,135,106,138,137,154,167,137,175,133,144,240,49,223,17,137,17,61"
  alt="Houses in South Katoomba" href="south.html">
  </map>

때때로, 여러 이미지들로부터 함성 사진을 생성하는 경우, 이미지들의 하나 이상을 링크하고 싶을 수 있습니다. 링크의 목적을 설명하기 위해 각 링크된 이미지에 대해 alt 속성(attribute)을 제공하세요.

다음 예에서, 합성 사진은 "crocoduck"을 나타내는데 사용됩니다; 악어의 일부와 오리의 일부가 되는 진화적 원리들을 무시하는 가상의 창조물. crocoduck과 상호 작용하도록 요구되고, 주의를 기울일 필요가 있습니다...

crocodile’s angry, chomping headduck’s soft, feathery body

<h1>The crocoduck</h1>
<p>You encounter a strange creature called a "crocoduck".
The creature seems angry! Perhaps some friendly stroking will help to calm
it, but be careful not to stroke any crocodile parts. This would just enrage
the beast further.</p>
<a href="?stroke=head"><img src="crocoduck1.png" alt="Stroke crocodile’s angry, chomping head"></a>
<a href="?stroke=body"><img src="crocoduck2.png" alt="Stroke duck’s soft, feathery body"></a>
4.7.5.1.14. 사진 이미지들

사진이나 그래픽 이미지는 개체, 사람, 풍경, 추상화, 기타 등등의 시각적 표현을 포함합니다. 이 비 텍스트 콘텐트는, [WCAG20] 정상 시력자에게 시각적으로 특별한 의미가 있는 대량의 정보를 전달하거나 특정한 감각적 경험을 제공, [WCAG20] 할 수 있습니다. 그 예들은 사진, 그림, 도안, 삽화를 포함합니다.

그림에 대한 적절한 대체 텍스트는 간단한 설명이나 이름입니다 [WCAG20]. 모든 대체 텍스트 작성 결정에서와 같이, 그림에 대한 적절한 대체 텍스트들을 작성하는 것은 사람의 판단을 요구합니다. 텍스트 값은 이미지가 사용되는 맥락과 페이지 작성자의 문체에 따라 주관적입니다. 따라서, 어떤 특정 이미지에 대해 "정확"하거나 "옳은" 하나의 alt 텍스트는 존재하지 않습니다. 비 텍스트 콘텐트의 간단한 설명을 제공하는 짧은 대체 텍스트를 제공하는 것뿐 아니라, 다른 도구들을 통해 보충 콘텐트를 제공하는 것은 적절한 경우 유용할 수 있습니다.

이 첫 번째 예는 사진 공유 사이트에 업로드 된 이미지를 보여줍니다. 사진은 욕조에 앉아있는 고양이입니다. 이미지는 img 요소(element)의 alt 속성(attribute)을 사용하여 제공된 대체 텍스트를 가집니다. 그것은 또한 figure 요소(element) 내에 img 요소(element)를 포함하는 것과 캡션 텍스트를 식별하기 위한 figcaption 요소(element)를 사용하는 것에 의해 제공된 캡션을 가집니다.

Lola the cat sitting under an umbrella in the bath tub.

Lola prefers a bath to a shower.

<figure>
<img src="664aef.jpg" alt="Lola the cat sitting under an umbrella in the bath tub.">
<figcaption>Lola prefers a bath to a shower.</figcaption>
</figure>
이 예는 이미지의 제목이 해석에 대해 열려있기 때문에 완전한 설명이 거의 불가능한 이미지의 예입니다. 이미지는 alt 속성(attribute)에 이미지를 볼 수 없는 사용자에게 이미지가 무엇인지의 느낌을 제공하는 대체 텍스트를 가집니다. 이것은 또한 figure 요소(element)에 img 요소(element)를 포함시키고 캡션 텍스트를 식별하기 위해 figcaption 요소(element)를 사용하여 제공된 캡션을 가집니다.

An abstract, freeform, vertically symmetrical, black inkblot on a light background.

The first of the ten cards in the Rorschach test.

<figure>
  <img src="Rorschach1.jpg" alt="An abstract, freeform, vertically symmetrical, black inkblot on a light background.">
  <figcaption>The first of the ten cards in the Rorschach test.</figcaption>
  </figure>
4.7.5.1.15. 웹캠 이미지

웹캠 이미지들은 주기적으로 자동으로 업데이트되는 정적 이미지들입니다. 일반적으로 이미지들은 고정된 시점에서의 이미지이고, 이미지들은 카메라로부터 업로드되는 각 새로운 이미지로서 자동으로 페이지에 업데이트 될 수 있거나 사용자가 업데이트 된 이미지를 보기 위해 페이지 새로 고침이 요구될 수 있습니다. 이 예들은 교통 상황과 날씨 카메라들을 포함합니다.

이 예는 꽤 전형적입니다; 제목(title)과 타임 스탬프가 웹캠 소프트웨어에 의해 자동으로 생성되어 이미지에 포함됩니다. 텍스트 정보가 이미지에 포함되지 않았다면 더 좋았을 것이지만, 그것이 이미지의 일부이기 때문에 대체 텍스트의 일부로 그것을 포함합니다. 캡션은 또한 figurefigcaption 요소(element)들을 사용하여 제공됩니다. 이미지가 건물 근처 현재 날씨의 시각적 정보를 전달하기 위해 제공되는 것처럼, 지역 일기 예보로의 링크가 제공 되고, 자동으로 생성되고 업로드 된 웹캠 이미지들처럼, 대체 텍스트로서 그 정보를 제공하는 것은 실행 불가능할 수 있습니다.

alt 속성(attribute)의 텍스트는 음성 소프트웨어에 텍스트를 알리는 경우 더 이해하기 쉽도록 설계된, 타임 스탬프의 문제 버전을 포함합니다. 대체 텍스트는 또한 기상 조건들과 하루의 시간이 변하기는 하지만, 이미지에서 보여질 수 있는 변하지 않는 것의 일부 양상의 설명을 포함합니다.

Sopwith house weather cam. Taken on the 21/04/10 at 11:51 and 34 seconds. In the foreground are the safety
  rails on the flat part of the roof. Nearby ther are low rize industrial buildings, beyond those are block of flats. In the distance there’s a
  church steeple.

View from the top of Sopwith house, looking towards North Kingston. This image is updated every hour.

View the latest weather details for Kingston upon Thames.

<figure>
  <img src="webcam1.jpg" alt="Sopwith house weather cam. Taken on the 21/04/10 at 11:51 and 34 seconds.
  In the foreground are the safety rails on the flat part of the roof. Nearby there are low rize industrial buildings,
  beyond are blocks of flats. In the distance there’s a church steeple.">
  <figcaption>View from Sopwith house, looking towards north Kingston. This image is updated every hour.</figcaption>
  </figure>
  <p>View the <a href="https://news.bbc.co.uk/weather/forecast/4296?area=Kingston">latest weather details</a> for Kingston upon Thames.</p>
4.7.5.1.16. 게시 시점에 대체 텍스트가 불가한 경우

어떤 경우 이미지는 발행된 문서에 포함되지만, 작성자가 적절한 대체 텍스트를 제공할 수 없습니다. 그러한 경우 최소한의 요구사항은 다음 조건 하에 figurefigcaption 요소(element)들을 사용하여 이미지에 대한 캡션을 제공하는 것입니다:

다시 말해, figure의 유일한 콘텐트는 img 요소(element)와 figcaption 요소(element)이고, figcaption 요소(element)는 (캡션) 콘텐트를 포함해야(must) 합니다.

그러한 경우는 최소한으로 유지되어야 합니다. 실제 대체 텍스트를 제공할 수 있는 능력을 가지는 작성자의 최소한의 가능성이라도 있다면, alt 속성(attribute)을 생략하는 것은 허용 될 수 없습니다.

이 예에서, 누군가 사진 공유 사이트에 다수의 이미지의 대량 업로드의 일부로 사진을 업로드 합니다. 사용자는 이미지에 대한 대체 텍스트나 캡션을 제공하지 않았습니다. 사이트의 작성 도구가 이미지에 대해 가지고 있는 어떤 유용한 정보를 사용하여 자동으로 캡션을 삽입합니다. 이 경우 그것은 파일 이름과 사진이 찍힌 날짜입니다.

아래 예에서 캡션 텍스트는 적절한 대체 텍스트가 아니며 웹 접근성 지침 2.0에 준하지 않습니다. [WCAG20]

no text alternative provided

clara.jpg, taken on 12/11/2010.

<figure>
<img src="clara.jpg">
<figcaption>clara.jpg, taken on 12/11/2010.</figcaption>
</figure>

이 예에서까지도 figcaption 요소(element)에 여전히 가능한 많은 유용한 정보가 포함되는 것에 주목하세요.

이 두 번째 예에서, 누군가 사진 공유 사이트에 사진을 업로드합니다. 그녀는 대체 텍스트가 아니라 이미지에 대한 캡션을 제공했습니다. 이는 사이트가 사용자에게 alt 속성(attribute)에 대체 텍스트를 추가하기 위한 수단을 제공하지 않기 때문일 수 있습니다.

no text alternative provided

Eloisa with Princess Belle

<figure>
<img src="elo.jpg">
<figcaption>Eloisa with Princess Belle</figcaption>
</figure>
때때로 이미지의 전체 의미는 텍스트로 설명이 불가능한 것이고, 사용자가 설명을 제공합니다. 예를 들어, 이미지를 표시하고 정확한 대체 텍스트를 가진 페이지를 작성하는 때의 목적을 위해 정확하게 대체 텍스트를 요구하는 소프트웨어. 그러한 페이지는 이와 같이, 이미지의 표를 가질 수 있습니다:
<table>
  <tr><tr> <th> Image <th> Description<tr>
  <td>
  <figure>
  <img src="2421.png">
  <figcaption>Image 640 by 100, filename 'banner.gif'</figcaption>
  </figure>
  <td> <input name="alt2421">
  <tr>
  <td> <figure>
  <img src="2422.png">
  <figcaption>Image 200 by 480, filename 'ad3.gif'</figcaption>
  </figure>
  <td> <input name="alt2422">
  </table>

어떤 사용자들은 이미지를 전혀 사용할 수 없기 때문에 (예를 들어, 눈이 보이지 않기 때문에) alt 속성(attribute)은 위의 예에서와 같이, 대체 텍스트가 사용 불가능하고 어떠한 것도 사용 가능하게 만들 수 없는 경우에만 생략되는 것이 허용됩니다.

4.7.5.1.17. 사용자에 대해 의도되지 않은 이미지

일반적으로 작성자들은 이미지들을 보여주는 것 외 다른 목적들로 img 요소(element)들을 사용하는 것을 피해야 합니다.

img 요소(element)가 이미지를 보여주는 것 외 다른 목적들로 사용되고 있다면, 예를 들어 페이지 뷰를 카운트하는 서비스의 일부로, 빈 alt 속성(attribute)을 사용하세요.

img 요소(element)의 예는 웹 페이지 통계를 수집하는데 사용됩니다. alt 속성(attribute)은 이미지가 의미(meaning)를 가지지 않기 때문에 비어있습니다.
<img src="https://server3.stats.com/count.pl?NeonMeatDream.com" width="0" height="0" alt="">

위 예에 대해서 widthheight 속성(attribute)들은 0으로 설정되도록 사용하는 것이 권장됩니다.

또 다른 사용 예는 spacer.gif와 같은 이미지가 콘텐트의 위치를 보조하는데 사용되는 경우입니다. alt 속성(attribute)은 이미지가 의미(meaning)를 가지지 않기 때문에 비어있습니다.
<img src="spacer.gif" width="10" height="10" alt="">

콘텐트를 배치하기 위해 img 요소(element)들을 사용하는 대신 CSS를 사용하도록 권장됩니다.

4.7.5.1.18. 아이콘 이미지

아이콘은 보통 프로그램, 동작, 데이터 파일, 컨셉을 나타내는 간단한 그림입니다. 아이콘들은 시각 브라우저들의 사용자들이 한 눈에 기능을 인식할 수 있도록 돕기 위해 의도됩니다.

아이콘이 동일한 의미(meaning)를 전달하는 텍스트에 대해 추가된 것인 경우 빈 alt 속성을 사용하세요.

이 예에서, 사이트의 홈 페이지를 가리키는 링크를 가지고 있고, 이 링크는 집 아이콘 이미지와 텍스트 "home"을 포함합니다. 이미지는 빈 alt 텍스트를 가집니다.

A house icon next to the word 'home'.

<a href="home.html"><img src="home.gif" width="15" height="15" alt="">Home</a>

이미지들이 이 방법으로 사용되는 경우, CSS를 사용하여 이미지를 추가하는 것 또한 적절할 것입니다.

#home:before
{
content: url(home.png);
}

<a href="home.html" id="home">Home</a>
이 예에, 경고 아이콘을 가진 경고 메세지가 있습니다. 단어 "Warning!"이 이미지 옆에 강조된 텍스트에 있습니다. 아이콘에 의해 전달된 정보는 불필요하기 때문에 img 요소(element)는 빈 alt 속성(attribute)이 제공되었습니다.

Warning! Warning! Your session is about to expire.

<p><img src="warning.png" width="15" height="15" alt="">
<strong>Warning!</strong>
Your session is about to expire</p>

아이콘이 텍스트 내에 사용 가능하지 않은 추가적인 정보를 전달하는 경우, 대체 텍스트를 제공하세요.

이 예에, 경고 아이콘을 가진 경고 메세지가 있습니다. 아이콘은 메세지의 중요성을 강조하고 콘텐트의 특정한 유형으로서 그것을 식별합니다.

Warning! Your session is about to expire.

<p><img src="warning.png" width="15" height="15" alt="Warning!">
Your session is about to expire</p>
4.7.5.1.19. 로고, 휘장, 깃발, 엠블럼

많은 페이지들은 회사, 조직, 프로젝트, 밴드, 소프트웨어 패키지, 국가, 기타 단체들을 대표하는 로고, 휘장, 깃발, 엠블럼들을 포함합니다. 모든 이미지가 그렇듯, 적절한 대체 텍스트로서 고려될 수 있는 것은 이미지가 사용되는 맥락과 주어진 맥락에서 그것이 어떤 기능을 제공하는가에 달려있습니다.

로고가 링크의 유일한 콘텐트라면, alt 속성(attribute)에 링크 대상에 대한 간단한 설명을 제공하세요.

이 예는 HTML 명세로의 링크의 유일한 콘텐트로서 HTML5 로고의 사용을 보여줍니다.

HTML 5.1 Nightly specification

<a href="https://w3c.github.io/html/">
<img src="HTML5_Logo.png" alt="HTML 5.1 specification"></a>

로고가 단체를 나타내는데 사용되는 것이라면, 예를 들어, 페이지 제목(heading)으로, 대체 텍스트로서 로고에 의해 표현되는 단체의 이름을 제공하세요.

이 예는 자신을 나타내는데 사용되는 WebPlatform.org 로고의 사용을 보여줍니다.

WebPlatform.org and other developer resources

<h2><img src="images/webplatform.png" alt="WebPlatform.org"> and other developer resources<h2>

위 예에서 대체 텍스트는 이미지 콘텐트의 유형을 설명하기 위해 단어 "logo"도 포함할 수 있습니다. 그러한 경우, 이 정보를 상세히 기술하기 위해 각괄호가 사용되도록 제안됩니다: alt="[logo] WebPlatform.org".

로고가 그것이 나타내는 것의 이름 옆에 사용된다면, 로고는 추가적인 것입니다. 대체 텍스트가 이미 제공된 것 처럼 빈 alt 속성(attribute)을 포함시키세요.

이 예는 조직의 이름 옆에 나타나는 로고의 사용을 보여줍니다.

WebPlatform.org

<img src="images/webplatform1.png" alt=""> WebPlatform.org

로고가 주제나 단체 로고가 나타내는 것을 설명하는 텍스트와 함께 사용된다면, 로고를 설명하는 대체 텍스트를 제공하세요.

이 예는 주제가 로고가 나타내는 것을 설명하는 텍스트 옆의 로고의 사용을 보여줍니다.

HTML5 logo: Shaped like a shield with the text 'HTML' above and the numeral '5' prominent on the face of the shield.

HTML is a language for structuring and presenting content for the World Wide Web, a core technology of the Internet. It is the latest revision of the HTML standard (originally created in 1990 and most recently standardized as HTML 4.01 in 1997) and currently remains under development. Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers etc.).

<p><img src="HTML5_Logo.png" alt="HTML5 logo: Shaped like a shield with the
text 'HTML' above and the numeral '5' prominent on the face of the shield."></p>

Information about HTML
4.7.5.1.20. CAPTCHA 이미지

CAPTCHA는 "컴퓨터와 인간을 구별하는 완전히 자동화 된 공공 튜링 테스트"를 나타냅니다. CAPTCHA 이미지들은 콘텐트가 컴퓨터가 아닌 사람에 의해 접근되고 있는지를 확인 하기 위한 보안 목적으로 사용됩니다. 이 인증은 이미지의 시각적 확인을 통해 이루어집니다. CAPTCHA는 일반적으로 사용자가 다시 타이핑하기 위한 글자나 단어를 가진 이미지를 나타냅니다. 이미지는 보통 왜곡되고 글자들을 읽기 어렵게 만들기 위해 적용된 일부 노이즈를 가집니다.

CAPTCHA의 접근성을 향상시키기 위해 이미지의 목적을 식별하고 설명하는 대체 텍스트들을 제공하고, 다른 유형의 감간 인식에 대한 출력 모드를 사용하여 CAPTCHA의 대체 형식을 제공하세요. 예를 들어 시각적인 이미지와 함께 대체 음성을 제공하세요. 시작적 이미지의 바로 옆에 음성 옵션을 위치 시키세요. 이것은 도움이 되지만, 사운드 카드가 없는 사람, 청각-시각장애인, 몇몇 제한된 청력을 가진 사람들에 대해 요전히 문제가 됩니다. 다른 방법은 시각 이미지와 함께 질문을 묻는 양식을 포함하는 것입니다. 이것은 도움이 되지만 인지 장애를 가진 사람들에 대해 문자가 될 수 있습니다.

CAPTCHA의 모든 형식은 장애를 가진 사용자들에 대해 허용 될 수 없는 참여 장벽을 가져오기 때문에, CAPTCHA에 대해 사용되는 대안들이 강력하게 권장됩니다. 좀 더 자세한 정보는 Inaccessibility of CAPTCHA에서 사용 가능합니다.

이 예는 텍스트의 왜곡된 이미지를 사용하는 CAPTCHA 검사를 보여줍니다. alt 속성(attribute) 내의 대체 텍스트는 이미지 콘텐트에 접근할 수 없는 경우의 사용자에 대한 지시사항들을 제공합니다.

captcha containing the words 'aides' and 'sprucest'. The letters are distorted and the color of the letters and background is partially inverted,

Example code:

<img src="captcha.png" alt="If you cannot view this image an audio challenge is provided.">
<!-- audio CAPTCHA option that allows the user to listen and type the word -->
<!-- form that asks a question -->
4.7.5.1.21. picture 요소(element) 내의 이미지

picture 요소(element)와 그것이 포함하는 source 요소(element)들은 사용자들에 대한 의미(semantic)을 가지지 않으므로, img 요소(element)나 그것의 대체 텍스트만이 사용자들에게 표시됩니다. img 요소(element)에 대한 대체 텍스트를 picture 요소(element)에 있는 것과 관계 없이 제공하세요. 이미지들에 대한 유용한 alt 텍스트를 제공하는 방법데 대한 자세한 내용을 위해 이미지들에 대한 대체 텍스트로서 동작하도록 텍스트를 제공하기 위한 요구사항을 참조하세요.

picture에 의존하는 art directed 이미지들은 동일한 콘텐트를 (크기, 픽셀 밀도, 다른 식별 요소에 관계 없이) 그리도록 요구됩니다. 따라서 브라우저에 의해 선택되는 소스 파일에 관계 없이 이미지에 대한 적절한 대체 텍스트가 항상 동일할 것입니다.

<h2>Is it a ghost?</h2>
<picture>
  <source media="(min-width: 32em)" srcset="large.jpg">
  <img src="small.jpg" alt="Reflection of a girls face in a train window.">
</picture>

이미지의 크고 작은 버전들은 (두 버전 모두 데모 용으로 표시됩니다) 동일한 장면을 묘사합니다: 열차 창에 소녀 얼굴의 반사 장면은, 작은 버전 (작은 화면에 표시되는)이 잘렸지만, 주제나 alt 텍스트의 적절성에 영향을 주지 않습니다.

Reflection of a girls face in a train window. Reflection of a girls face in a train window.

4.7.5.1.22. 마크업 생성기들을 위한 지침

마크업 생성기들은 (WYSIWYG 작성도구들 같은), 가능한 어디든지, 그것들의 사용자들로부터 대체 텍스트를 얻어야(should) 합니다. 하지만, 많은 경우에, 이것은 가능하지 않을 것으로 인정됩니다.

링크들의 유일한 콘텐트인 이미지들에 대해, 마크업 생성기들은 대상의 제목이나 대상의 URL을 결정하기 위해 링크 대상을 검토해야(should)하고, 이 방법으로 얻어진 정보를 대체 텍스트로 사용해야 합니다.

캡션을 가지는 이미지들에 대해, 마크업 생성기들은 이미지의 캡션을 제공하기 위해 figurefigcaption 요소(element)들을 사용해야(should) 합니다.

최후의 수단으로, 구현자는 이미지가 어떤 정보도 추가하지 않지만 여전히 주변 콘텐트에 따라 다른 순수하게 장식 이미지라는 가정 하에 alt 속성(attribute)을 빈 문자열로 설정 해야(should) 하거나, 이미지가 콘텐트의 핵심 부분이라는 가정하에alt 속성(attribute)을 완전히 생략해야(should) 합니다.

마크업 생성기들은 대체 텍스트를 얻는 것이 불가능하고 때문에 alt 속성(attribute)이 생략된 img 요소(element)들에 generator-unable-to-provide-required-alt 속성(attribute)을 명시할 수 있습니다. 이 속성(attribute)의 값은 빈 문자열이어야(must) 합니다. 그 속성(attribute)들을 포함하는 문서들은 적합하지 않지만, 적합성 검사기들은 이 오류를 묵시적으로 무시할 것입니다.

이것은 최신의 자동화 적합성 검사기들이 가짜 대체 텍스트들과 올바른 대체 텍스트들을 구별할 수 없기 때문에, alt 속성(attribute)의 생략 오류를 가짜 대체 텍스트들을 제공하는 훨씬 더 엄청난 오류로의 교체가 강제되는 것으로부터 마크업 생성기들을 방지하기 위해 의도된 것입니다.

마크업 생성기들은 일반적으로 대체 텍스트로서 이미지 자신의 파일 이름을 사용하는 것을 방지해야(should) 합니다. 마찬가지로, 마크업 생성기들은 프리젠테이션 유저 에이전트들에 (예를 들어, 웹 브라우저들) 동일하게 사용 가능한 콘텐트로부터 대체 텍스트들을 생성하는 것을 방지해야(should) 합니다.

이것은, 나중에 페이지를 읽는 브라우저들이 사용자에 의해 업데이트 될 수 있는 반면에, 일단 페이지가 생성되면 일반적으로 업데이트 될 수 없기 때문에, 브라우저는 페이지가 생성될 때 마크업 생성기가 하는 것 보다 좀 더 최신의 그리고 미세하게 조정된 휴리스틱을 가질 가능성이 높습니다.

4.7.5.1.23. 적합성 검사기들을 위한 지침

적합성 검사기들은 아래 나열된 조건들 중 하나에 적용되지 않는 한 alt 속성(attribute)의 결핍을 오류로 보고해야(must) 합니다:

4.7.6. iframe 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
본문에 주어진 요구사항들을 따르는 텍스트
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - 리소스의 주소
srcdoc - iframe에 렌더링 할 문서
name - 중첩된 브라우징 컨텍스트의 이름
sandbox - 중첩된 콘텐트에 대한 보안 규칙들
allowfullscreen - iframe의 콘텐트가 requestFullscreen()를 사용하는 것을 허용할지 여부
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, document, img.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLIFrameElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString srcdoc;
  attribute DOMString name;
  [PutForwards=value] readonly attribute DOMTokenList sandbox;
  attribute boolean allowFullscreen;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
};

iframe 요소(element)는 중첩된 브라우징 컨텍스트나타냅니다.

src 속성(attribute)은 중첩된 브라우징 컨텍스트가 포함하는 페이지의 주소를 제공합니다. 이 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다.

srcdoc 속성(attribute)은 중첩된 브라우징 컨텍스트가 포함하는 페이지의 콘텐트를 제공합니다. 이 속성(attribute)의 값은 iframe srcdoc 문서의 소스입니다.

srcdoc 속성(attribute)이 존재한다면 주어진 순서에 따라 다음 구문 컴포넌트들로 구성되는 HTML 문법을 사용하는 값을 가져야(must) 합니다:

  1. 얼마든지의 주석들공백 문자들.
  2. 선택적으로, DOCTYPE.
  3. 얼마든지의 주석들공백 문자들.
  4. html 요소(element)의 형식으로, 루트 요소(element).
  5. 얼마든지의 주석들공백 문자들.

XML 문서들에 있는 iframe 요소(element)들에 대해, srcdoc 속성(attribute)이 존재한다면 XML 명세에 document라고 라벨링 된 생산물에 일치하는 값을 가져야(must) 합니다. [XML]

여기 블로그가 블로그 게시물 댓글들에 스크립트 인젝션으로부터 보호 추가 레이어로 이 기능을 지원하는 유저 에이전트들의 사용자들에게 제공하기 위해 아래 기술된 sandbox 속성(attribute)과 함께 srcdoc 속성(attribute)을 사용합니다:
<article>
  <h1>I got my own magazine!</h1>
  <p>After much effort, I’ve finally found a publisher, and so now I
  have my own magazine! Isn’t that awesome?! The first issue will come
  out in September, and we have articles about getting food, and about
  getting in boxes, it’s going to be great!</p>
  <footer>
  <p>Written by <a href="/users/cap">cap</a>, 1 hour ago.
  </footer>
  <article>
  <footer> Thirteen minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>did you get a cover picture yet?"></iframe>
  </article>
  <article>
  <footer> Nine minutes ago, <a href="/users/cap">cap</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe>
  </article>
  <article>
  <footer> Five minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>hey that’s earl’s table.
<p>you should get earl&amp;amp;me on the next cover."></iframe>
  </article>

따옴표를 이스케이프 되어야(have to) 하는 (그렇지 않으면 srcdoc 속성(attribute)들이 일찍 종료될 것입니다) 방식과 샌드박스 된 콘텐트에 언급된 앰퍼샌드들이 (예를 들어, 본문에서 URL들의 앰퍼샌드) 이중으로 이스케이프되어야(have to)하는 방식에 주목하세요 — 한 번은 앰퍼센드가 본래 srcdoc 속성(attribute)을 해석 할 때 보존되고, 샌드박스 된 콘텐트를 해석 할 때 자롯 해석되는 것으로부터 앰퍼샌드를 방지하기 위해 한 번 더.

게다가, iframe srcdoc 문서들DOCTYPE이 선택적이고, html, head, body 요소(element)들이 선택적 시작/종료 태그들을 가지며, iframe srcdoc 문서들title 요소(element) 역시 선택적이기 때문에, body 요소(element)의 콘텐츠만이 구문에서 문자 그대로 나타날 필요가 있으므로 srcdoc 속성(attribute) 내의 마크업은 전체 문서를 나타내는 것에도 불구하고 비교적 간결할 수 있습니다. 다른 요소(element)들은 암묵적으로만 여전히 존재합니다.

HTML 문법에서, 작성자들은 단지 속성(attribute) 콘텐트를 감싸기 위해 U+0022 따옴표 문자들 (")을 사용하고 이후 모든 U+0022 따옴표 문자 (")와 0026 앰퍼샌드 (&) 문자들을 이스케이프하고, 콘텐트의 안전한 삽입을 보장하기 위해 sandbox 속성(attribute)을 명시하는 것을 기억하기만 하면 됩니다.

XHTML 문법의 제한 때문에, XML에서 U+003C ~보다 작다 기호 문자 (<)도 이스케이프 될 필요가 있습니다. 속성(attribute)-값 정규화를 방지하기 위해, 일부 XML의 공백 문자들 — 특별히 U+0009 탭 문자 (tab), U+000A 라인피드 (LF), U+000D 캐리지 리턴 (CR) — 또한 이스케이프 될 필요가 있습니다. [XML]

src 속성(attribute)과 srcdoc 속성(attribute)이 모두 함께 명시되어 있다면, srcdoc 속성(attribute)이 우선됩니다. 이것은 작성자가 srcdoc 속성(attribute)을 지원하지 않는 레거시 유저 에이전트들에 대한 폴백 URL을 제공하는 것을 허용합니다.


iframe 요소(element)가 브라우징 컨텍스트를 가지는 문서에 삽입 되는 경우, 유저 에이전트는 중첩된 브라우징 컨텍스트를 생성해야(must) 하고, "처음"으로 iframe 속성(attribute)들을 처리해야(must) 합니다.

iframe 요소(element)가 문서로부터 제거 되는 경우, 유저 에이전트는 중첩된 브라우징 컨텍스트가 있다면 이를 폐기해야(must) 합니다.

이것은 unload 이벤트 발생 없이 일어납니다 (중첩된 브라우징 컨텍스트와 그것의 Document언로드가 아니라 폐기됩니다).

중첩된 브라우징 컨텍스트를 가진 iframe 요소(element)가 그것의 srcdoc 속성(attribute)이 설정, 변경, 제거 될 때마다, 유저 에이전트는 iframe 속성(attribute)들을 처리해야(must) 합니다.

마찬가지로, 중첩된 브라우징 컨텍스트를 가지지만 명시된 srcdoc 속성(attribute)이 없는 iframe 요소(element)가 그것의 src 속성(attribute)이 설정, 변경, 제거 될 때마다, 유저 에이전트는 iframe 속성(attribute)들을 처리해야(must) 합니다.

유저 에이전트가 iframe 속성(attribute)들을 처리하는 경우, 다음 목록에서 첫 번째 적절한 단계들을 수행해야(must) 합니다:

srcdoc 속성(attribute)이 명시되어 있다면

요소(element)의 자식 브라우징 컨텍스트url 목록about:srcdoc로 구성되고, 헤더 목록Content-Type/text/html로 구성되며, body가 속성(attribute)의 값이고, CSP 목록iframe 요소(element)의 노드 문서CSP 목록이며, HTTPS 상태iframe 요소(element)의 노드 문서HTTPS 상태인 새로운 응답으로 이동(navigate)시키세요.

결과 Documentiframe srcdoc 문서로 간주되어야(must) 합니다.

그렇지 않고, 요소(element)가 명시된 src 속성(attribute)을 가지지 않고 유저 에이전트가 "처음"으로 iframe 속성(attribute)들을 처리하고 있다면

iframe load event 단계들을 수행하기 위한 작업을 대기열에 넣습니다.

작업에 대한 작업 소스DOM 조작 작업 소스입니다.

그렇지 않으면
  1. 요소(element)가 명시된 src 속성(attribute)을 가지지 않거나, 그것의 값이 빈 문자열이라면, url을 문자열 "about:blank"로 둡니다.

    그렇지 않으면, src 속성(attribute)의 값을 iframe 요소(element)와 관련하여 해석 하세요.

    그것이 성공적이지 않다면, url를 문자열 "about:blank"로 둡니다. 그렇지 않으면 url결과 URL 문자열로 둡니다.

  2. 문서 조각 식별자를 무시하여, 활성 문서주소url가 동일한 조상 브라우징 컨텍스트가 존재한다면, 이 단계들을 중단합니다.

  3. 요소(element)의 자식 브라우징 컨텍스트url이동(navigate) 시키세요.

게다가, 그 이동 전에 요소(element)의 자식 브라우징 컨텍스트활성 문서가 새로운 이동의 시점에 완전히 로드 되지 않았다면, 이동교체 활성화를 가지고 완료되어야(must) 합니다.

마찬가지로, iframe 속성(attribute)들 처리 알고리즘이 호출되는 경우, 자식 브라우징 컨텍스트세션 히스토리가 오직 하나의 Document를 포함하고, 그것이 자식 브라우징 컨텍스트가 생성 될 때 생성 된 about:blank Document였다면, 그 알고리즘에서 유저 에이전트의 요구된 모든 이동교체 활성화를 가지고 완료되어야(must) 합니다.

iframe 내의 Document완전히 로드 된것으로 표기되는 경우, 유저 에이전트는 병렬로 iframe load 이벤트 단계들을 수행해야(must) 합니다.

그것이 생성될 때 어떤 다른 데이터도 그 내부에서 로드되지 않는다면 load 이벤트도 iframe 요소(element)에서 발생됩니다.

Documentiframe load in progress 플래그와 mute iframe load 플래그를 가집니다. Document가 생성될 때, 이 플래그들은 그 Document에 대해 해제되어야(must) 합니다.

iframe load 이벤트 단계들은 다음과 같습니다:

  1. child documentiframe 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로 둡니다.
  2. child document가 그것의 설정된 mute iframe load 플래그를 가진다면, 이 단계들을 중단합니다.
  3. child documentiframe load in progress 플래그를 설정합니다.
  4. iframe 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생 시킵니다.
  5. child documentiframe load in progress 플래그를 해제합니다.

이것은, 스크립팅과 함께, 로컬 네트워크의 HTTP 서버들의 URL 공간을 살피는데 사용될 수 있습니다. 유저 에이전트들은 이 공격을 완화시키기 위해 위에 기술된 것 보다 엄격한 cross-origin 접근 제어 정책들을 구현할 수 있지만, 불행하게도 그 정책들은 일반적으로 기존의 웹 콘텐트와 호환되지 않습니다.

iframe브라우징 컨텍스트활성 문서post-load 작업들에 대해 준비되지 않은 경우와, iframe 내의 모든 것이 iframe브라우징 컨텍스트활성 문서load 이벤트를 지연 중인 경우와, iframe브라우징 컨텍스트load 이벤트 지연 모드에 있는 경우, iframe은 그 문서의 load 이벤트를 지연시켜야(must) 합니다.

load 이벤트의 처리 동안, iframe 내의 브라우징 컨텍스트가 다시 이동되었다면, 좀 더 load 이벤트를 지연시킬 것입니다.

요소(element)가 생성되었을 때, srcdoc 속성(attribute)이 설정되어 있지 않고, src 속성(attribute) 또한 설정되어 있지 않거나 설정되었지만 그 값이 분석(resolve)될 수 없다면, 브라우징 컨텍스트는 초기 about:blank 페이지에 남을 것입니다.

사용자가 이 페이지로부터 다른 곳으로 이동한다면, iframe의 해당하는 WindowProxy 객체는 새로운 Document 객체들에 대한 새로운 Window 객체들을 대리(proxy)할 것이지만, src 속성(attribute)는 변경하지 않을 것입니다.


name 속성(attribute)이 있다면, 유효한 브라우징 컨텍스트 이름이어야(must) 합니다. 주어진 값은 중첩된 브라우징 컨텍스트를 이름 짓는데 사용됩니다. 브라우징 컨텍스트가 생성될 때, 속성(attribute)이 존재한다면 브라우징 컨텍스트 이름은 이 속성(attribute)의 값으로 설정되어야(must) 합니다; 그렇지 않으면, 브라우징 컨텍스트 이름은 빈 문자열로 설정되어야(must) 합니다.

name 속성(attribute)이 설정될 때 마다, 중첩된 브라우징 컨텍스트이름은 새로운 값으로 변경되어야(must) 합니다. 속성(attribute)이 제거 되었다면, 브라우징 컨텍스트 이름은 빈 문자열로 설정되어야(must) 합니다.


sandbox 속성(attribute)이 명시된 경우, iframe에 의해 관리되는 모든 콘텐트에 대한 별도의 제한 사항들의 세트를 가능하게 합니다. 그 값은 ASCII 대소문자 구분 없이 공백으로 분리된 고유한 토큰들의 순서없는 세트이어야(must) 합니다. 허용된 값들은 allow-forms, allow-pointer-lock, allow-popups, allow-same-origin, allow-scripts, allow-top-navigation 입니다.

속성(attribute)이 설정 된 경우, 콘텐트는 고유 출처, 양식, 스크립트들, 비활성화 된 다양한 곤란한 가능성이 있는 API들로 취급되고, 링크들은 다른 브라우징 컨텍스트들을 대상으로 하는 것을 방지하고, 플러그인들은 보호됩니다. allow-same-origin 키워드는 콘텐트가 고유 출처에 강제되는 것 대신 그것의 실제 출처의 것으로 취급되는 것을 야기합니다; allow-top-navigation 키워드는 콘텐트가 그것의 최상위 브라우징 컨텍스트이동하는 것을 허용하고; allow-forms, allow-pointer-lock, allow-popups, allow-scripts 키워드들은 각각 양식들, 포인터 잠금 API, 팝업, 스크립트들을 재활성화 시킵니다. [POINTERLOCK]

삽입 된(embedded) 페이지가 iframe을 포함하는 페이지로서 동일 출처를 가지는 경우 allow-scriptsallow-same-origin 키워드들을 모두 함께 설정하는 것은 효과적으로 완전히 샌드박스에서 벗어나, 삽입 된(embedded) 페이지가 sandbox 속성(attribute)를 쉽게 제거하고 그것을 리로드 하는 것을 허용합니다.

이 플래그들은 iframe중첩된 브라우징 컨텍스트이동 되는 경우에만 적용됩니다. 그것들을 제거하거나, 전체 sandbox 속성(attribute)을 제거하는 것은 이미 로드된 페이지에 아무런 영향을 가지지 않습니다.

잠재적으로 악의적인 파일들은 iframe 요소(element)를 포함하는 파일로 동일한 서버로부터 제공되지 않아야(should) 합니다. 공격자가 사용자에게 악의적인 콘텐트로 직접 방문하도록 납득 시킬 수 있다면, 샌드박스 된 악의적인 콘텐트는 iframe 안에서보다 최소한의 도움입니다. 악의적인 HTML 콘텐트에 의해 야기될 수 있는 피해를 최소화 하기 위해, 별도로 지정된 도메인으로부터 제공되어야(should) 합니다. 다른 도메인을 사용하는 것은, 사용자가 sandbox 속성(attribute)의 보호 없이 그 페이지들을 직접 방문하도록 속임에도 불구하고, 파일 내 스크립트가 사이트를 공격하는 것을 불가능하게 만드는 것을 보장합니다.

sandbox 속성(attribute)을 가진 iframe 요소(element)가 그것의 생성된 중첩 브라우징 컨텍스트를 가지는 (초기 about:blank Document가 생성되기 전에) 경우와, iframe 요소(element)가 중첩 브라우징 컨텍스트를 가지는 동안 sandbox 속성(attribute)이 설정되거나 변경되는 경우, 유저 에이전트는 input으로서 속성(attribute)의 값과 출력으로서 iframe 요소(element)의 중첩된 브라우징 컨텍스트iframe sandboxing 플래그 설정을, 그리고 iframeallowfullscreen 속성(attribute)를 가진다면 allow fullscreen flag를 사용하여 샌드박싱 지시를 해석해야(must)합니다.

iframe 요소(element)가 중첩된 브라우징 컨텍스트를 가지는 동안 sandbox 속성(attribute)이 제거되는 경우, 유저 에이전트는 출력으로 iframe 요소(element)의 중첩된 브라우징 컨텍스트iframe 샌드박싱 플래그 설정을 비워야(must) 합니다.

이 예에서, 완전히 알수 없는, 잠재적으로 악의적일 수 있는, 사용자가 제공한 HTML 콘텐트가 페이지에 삽입되어 있습니다. 그것은 별도의 도메인으로부터 제공되었기 때문에, 모든 정상 교차 사이트 제약사항들에 의해 영향을 받습니다. 게다가, 삽입된 페이지는 스크립팅 비활성화, 플러그인 비활성화, 양식 비활성화 되고, 다른 프레임들이나 자신 이외의 창들을 (혹은 다른 프레임들이나 그 자신을 삽입하는 창들) 이동할 수 없습니다.
<p>We’re not scared of you! Here is your content, unedited:</p>
<iframe title="Example iframe" sandbox src="https://usercontent.example.net/getusercontent.cgi?id=12193"></iframe>

공격자가 사용자로 하여금 그 페이지에 직접 방문하도록 납득시킨다면, 페이지는 사용자가 페이지 내에서 발견되는 공격에 취약하도록 만드는 사이트의 출처의 컨텍스트에서 수행하지 않기 때문에 별도의 도메인을 사용하는 것이 중요합니다.

이 예에서, 다른 사이트로부터 가젯이 삽입됩니다. 가젯은 스크립팅과 양식이 활성화 되어있고, 그것의 발신 서버와 통신하는 것을 허용하여, 원본 샌드박스 제약 사항들이 해제 되어 있습니다. 하지만 플러그인들과 팝업들이 비활성화 된 것처럼, 멀웨어와 다른 교란에 노출되는 사용자의 위험을 줄이는 것에 여전히 유용합니다.
<iframe title="Maps" sandbox="allow-same-origin allow-forms allow-scripts"
        src="https://maps.example.com/embedded.html"></iframe>
다음 코드 조각을 포함하는 파일 A를 가정해보세요:
<iframe title="Example iframe" sandbox="allow-same-origin allow-forms" src=B></iframe>

아이프레임을 포함하는 파일 B도 가정해보세요:

<iframe title="Example iframe" sandbox="allow-scripts" src=C></iframe>

또, 링크를 포함하는 파일 C를 가정해보세요:

<a href=D>Link</a>

이 예에서, 모들 파일들이 text/html로 제공된다고 가정하세요.

이 시나리오에서 페이지 C는 모두 샌드박싱 플래그 설정을 가집니다. A의 iframe은 비활성화된 스크립트들을 가지므로 스크립트들은 비활성화 되고, 이것은 B의 iframe에서 allow-scripts 키워드 설정을 재정의합니다. (B의) 내부 iframeallow-scripts 키워드를 가지지 않으므로 양식들 또한 비활성화됩니다.

이제 A의 스크립트가 A와 B의 모든 sandbox 속성(attribute)들을 제거한다고 가정해보세요. 이것은 즉시 아무 것도 변경시키지 않을 것입니다. 사용자가 B의 iframe으로 페이지 D를 로딩하는 C의 링크를 클릭했다면, 페이지 D는 이제 B의 iframe이 페이지 B가 로드되었을 때 A의 iframe에서 중첩된 브라우징 컨텍스트의 상태를 가졌기 때문에 allow-same-originallow-forms 키워드 설정을 가진 것처럼 수행합니다.

일반적으로 말해서, 동적으로 sandbox 속성(attribute)을 제거하거나 변경하는 것은 그것이 무엇을 허용할 것이고 무엇을 허용하지 않을 것인지에 대해 판단하는 것을 꽤 어렵게 만들기 때문에 문제의 소지가 있습니다.


allowfullscreen 속성(attribute)은 불리언 속성(attribute)입니다. 이 속성(attribute)이 명시된 경우, iframe 요소(element)의 브라우징 컨텍스트 내의 Document 객체들이 requestFullscreen()를 사용하도록 설정되어야 합니다(다른 이유로 예를 들어, 이 속성 설정이 없는 다른 조상 iframe이 존재하여 차단되지 않는다면).

여기에서, iframe는 비디오 사이트로부터 플레이어를 삽입하는데 사용됩니다. allowfullscreen 속성(attribute)는 플레이어가 그것의 비디오를 전체화면으로 보여주도록 활성화 할 필요가 있습니다.
<article>
  <header>
  <p><img src="/usericons/1627591962735"> <b>Fred Flintstone</b></p>
  <p><a href="/posts/3095182851" rel=bookmark>12:44</a><a href="#acl-3095182851">Private Post</a></p>
  </header>
  <main>
  <p>Check out my new ride!</p>
  <iframe title="Video" src="https://video.example.com/embed?id=92469812" allowfullscreen></iframe>
  </main>
</article>

iframe 요소(element)는 삽입된 콘텐트가 특정 치수들을 (예를 들어, 명확하게 정의된 치수들을 가지는 광고) 명시하는 경우들에 대해 치수 속성(attribute)들을 지원합니다.

iframe 요소(element)는 명시된 초기 콘텐츠가 성공적으로 사용되든 상관없이 항상 중첩된 브라우징 컨텍스트를 생성하기 때문에, 결코 폴백 콘텐트를 가지지 않습니다.


iframe 요소(element)들의 후손들은 아무 것도 나타내지 않습니다. (iframe 요소(element)들을 지원하지 않는 레거시 유저 에이전트들에서, 콘텐츠는 폴백 콘텐트로 수행될 수 있는 마크업으로 해석될 것입니다.)

HTML 문서들에 사용되는 경우, 컨텍스트 요소(element)로서 iframe 요소와 input으로서 텍스트 콘텐츠를 가지고 HTML 조각 해석 알고리즘을 수행하는 것이 해석 오류 발생 없이, 목록 내 아무 곳에 있거나 요소(element)들의 후손들로 존재하는 script 요소(element)들 없이, 자체적으로 규칙을 준수하는 목록 내 모든 요소(element)들 (그들의 후손들을 포함하여)과 함께 모든 어구(phrasing) 콘텐트인 노드들의 목록을 야기해야(must) 하는 텍스트를 제외하고, iframe 요소(element)들의 허용된 콘텐트 모델은 텍스트입니다.

iframe 요소(element)는 XML 문서들에서 비어 있어야(must) 합니다.

HTML 해석기iframe 요소(element) 내부 마크업을 텍스트로 취급합니다.


IDL 속성(attribute)들 src, srcdoc, name, sandbox는 각각 동일한 이름의 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

sandboxDOMTokenList에 대한 지원되는 토큰들sandbox 속성(attribute)에 정의된 값들이 허용되고 유저 에이전트들에 의해 지원됩니다.

allowFullscreen IDL 속성(attribute)는 allowfullscreen 콘텐트 속성(attribute)을 반영해야(must) 합니다.

contentDocument IDL 속성(attribute)은 iframe 요소(element)의 중첩된 브라우징 컨텍스트가 있다면 그리고 그것의 출처현직 설정 객체에 의해 명시된 출처로서 동일 출처 도메인활성 문서Document 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

contentWindow IDL 속성(attribute)은 iframe 요소(element)의 중첩된 브라우징 컨텍스트WindowProxy 객체가 있다면 WindowProxy 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

여기 광고 중개인으로부터의 광고를 포함하기 위해 iframe을 사용하는 페이지의 예가 있습니다:
<iframe title="Advert" src="https://ads.example.com/?customerid=923513721&amp;format=banner"
        width="468" height="60"></iframe>

4.7.7. embed 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
대화형(interactive) 콘텐트.
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
없음.
text/html에서 태그 생략:
종료 태그 없음.
콘텐트 속성(attribute)들:
범용 속성(attribute)들
src - Address of the resource
type - Type of embedded resource
width - Horizontal dimension
height- Vertical dimension
네임스페이스를 가지지 않는 모든 다른 속성(attribute) (본문 참고).
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, documentimgpresentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLEmbedElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
  attribute DOMString width;
  attribute DOMString height;
  legacycaller any (any... arguments);
};
embed 요소(element)에 의해 인스턴스화 된 콘텐트의 유형에 따라, 노드 또한 다른 인터페이스들을 지원할 수 있습니다.

embed 요소(element)는 외부 (일반적으로 비 HTML) 어플리케이션이나 대화형 콘텐트에 대한 통합점을 제공합니다.

src 속성(attribute)은 삽입되는 리소스의 주소를 제공합니다. 속성(attribute)이 존재한다면 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL을 포함해야(must) 합니다.

type 속성(attribute)이 존재한다면 인스턴스화 할 플러그인이 선택되는 MIME 타입 을 제공합니다. 값은 유효한 MIME 타입이어야(must) 합니다. type 속성(attribute)과 src 속성(attribute)이 모두 존재한다면, type 속성(attribute)은 src 속성(attribute)에 의해 주어진 리소스의 명시적인 Content-Type 메타데이터와 동일한 타입으로 명시해야(must) 합니다.

다음 조건들 중 하나라도 발생한다면, 요소(element)에 대해 인스턴스화 된 모든 플러그인은 제거되어야(must)하고, embed 요소(element )는 아무 것도 나타내지 않습니다:

  • 요소(element)가 src 속성(attribute)과 type 속성(attribute) 중 어떠한 것도 가지지 않는 경우.
  • 요소(element)가 조상 미디어 요소(element)를 가지는 경우 .
  • 요소(element)가 그것의 폴백 콘텐트를 보여주지 않는 조상 object 요소(element)를 가지는 경우.

embed 요소(element)가 다음 조건들을 모두 동시에 만족하는 경우 잠재적으로 활성이라고 불립니다:

잠재적으로 활성이 아니었던 embed 요소(element)가 잠재적으로 활성화 될 때마다, 그리고 잠재적 활성 embed 요소(element)가 남아있는 잠재적으로 활성이고 그것의 src 속성(attribute)이 설정, 변경, 혹은 제거되거나, 그것의 type 속성(attribute)이 설정, 변경, 혹은 제거 될 때 마다, 유저 에이전트는 embed 요소(element) 설정 단계들을 수행하기 위한 삽입(embed) 작업 소스를 사용하여 작업을 대기열에 넣어야(must) 합니다.

embed 요소(element) 설정 단계들은 다음과 같습니다:

  1. 이 요소(element)에 대해 embed 요소(element) 설정 단계들을 수행하기 위해 다른 작업이 대기열에 넣어진 이후라면, 이 단계들을 중단합니다.
  2. 요소(element)가 설정 된 src 속성(attribute)을 가진다면

    유저 에이전트는 요소(element)의 src 속성(attribute)의 값을 요소(element)에 관련하여 해석해야(must) 합니다. 그것이 성공적이라면, 유저 에이전트는 이 단계들을 수행해야(should) 합니다:

    1. requestURL결과 URL 문자열이고, 클라이언트가 요소(element)의 노드 문서Window 객체의 환경 설정 객체이고, 목적지가 "unknown"이며, 요소(element)가 브라우징 컨테스트 범위 출처를 가지지 않는다면 출처 헤더 생략 플래그가 설정되어 있고, 자격 증명 모드가 "include"이며, URL 자격 증명 사용 플래그가 설정된 새로운 요청으로둡니다.
    2. request가져옵니다(fetch).

    네트워킹 작업 소스에 의해 대기열에 넣어진 작업은 리소스가 가져와졌을(fetch) 때 다음 단계들을 수행해야(must) 합니다:

    1. 이 요소(element)에 대해 embed 요소(element) 설정 단계를 수행하기 위해 다른 작업이 대기열에 넣어진 이후라면, 이 단계들을 중단합니다.
    2. 삽입되는 콘텐트의 유형을 (유형을 결정하는 첫 번째 하위 단계에서 중지하여) 다음과 같이 결정합니다:

      1. 요소(element)가 type 속성(attribute)을 가지고 그 속성(attribute)의 값이 플러그인이 지원하는 유형이라면, type 속성(attribute)의 값은 콘텐트의 유형입니다.
      2. 그렇지 않고, 명시된 리소스의 URLURL 해석 알고리즘을 적용하는 것이 (모든 리다이렉트들 이후) 경로 컴포넌트가 플러그인이 지원하는 패턴과 일치하는 URL 레코드를 야기한다면, 콘텐트의 유형은 플러그인이 처리할 수 있는 유형입니다.

        예를 들어, 플러그인은 네 개 문자 문자열 ".swf"로 끝나는 경로 컴포넌트들을 가진 리소스를 처리할 수 있다고 말할 수 있습니다.

      3. 그렇지 않고, 명시된 리소스가 명시적 Content-Type 메타데이터를 가진다면, 그것이 콘텐트의 유형입니다.
      4. 그렇지 않으면 콘텐트는 유형을 가지지 않고 그것에 대한 적절한 플러그인이 없을 수 있습니다.
    3. 이전 단계가 콘텐트의 유형이 image/svg+xml이라고 결정했다면, 다음 하위 단계들을 수행합니다:

      1. embed 요소(element)가 중첩된 브라우징 컨텍스트와 연관되지 않는다면, 새롭게 생성된 중첩된 브라우징 컨텍스트와 연관짓고, 요소(element)가 name 속성(attribute)을 가진다면, 요소(element)의 중첩된 브라우징 컨텍스트브라우징 컨텍스트 이름을 이 속성(attribute)의 값으로 설정합니다.
      2. 중첩된 브라우징 컨텍스트를 가져와진 리소스로 교체 활성화소스 브라우징 컨텍스트로서 embed 요소(element)의 노드 문서브라우징 컨텍스트를 가지고 이동시킵니다. (embed 요소(element)의 src 속성(attribute)은 브라우징 컨텍스트가 다른 위치들로 더 이동된다면 업데이트 되지 않습니다.)
      3. embed 요소(element)는 이제 그것의 연관된 중첩된 브라우징 컨텍스트나타냅니다.
    4. 그렇지 않으면, 콘텐트 유형을 기반으로 적절한 플러그인을 찾고 인스턴스화 하고, 리소스의 콘텐트를 요소(element)에 대해 이전에 인스턴스화 된 플러그인들을 대신하여 그 플러그인에 전달합니다. embed 요소(element)는 이제 이 플러그인 인스턴스를 나타냅니다.

    5. 리소스나 플러그인이 완전히 로드되었을 때, 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

    리소스가 성공적으로 가져와(fetch)졌는지 아닌지의 여부는 (예를 들어, 응답 상태가 ok 상태였는지 여부) 콘텐트의 유형을 결정하는 중인 경우 와 리소스를 플러그인에 전달하는 중인 경우 무시되어야(must) 합니다.

    이것은 오류 응답들에도 불구하고 플러그인들에 대해 데이터를 반환하는 것을 허용합니다 (예를 들어, HTTP 500 서버 내부 오류 코드들은 여전히 플러그인 데이터를 포함할 수 있습니다).

    리소스를 가져오는(fetch) 것은 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

    요소(element)가 설정된 src 속성(attribute)을 가지지 않는다면

    유저 에이전트는 type 속성(attribute)의 값을 기반으로 적절한 플러그인을 찾고 인스턴스화 해야(should)합니다. embed 요소(element)는 이제 이 플러그인 인스턴스를 나타냅니다.

    플러그인이 완전히 로드되었을 때, 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

embed 요소(element)는 폴백 콘텐트를 가지지 않습니다. 유저 에이전트가 위 알고리즘에 대한 것을 찾고 인스턴스화 하기 위해 시도하는 경우 적절한 플러그인을 찾을 수 없다면, 유저 에이전트는 기본 플러그인을 사용해야(must)합니다. 이 기본 플러그인은 "지원되지 않는 형식"으로 나타내는 것처럼 단순할 수 있습니다.

잠재적으로 활성이었던 embed 요소(element)가 잠재적으로 활성화 되는 것을 중단 할 때마다, 그 요소(element)에 대해 인스턴스화 된 모든 플러그인은 언로드 되어야(must) 합니다.

플러그인이 인스턴스화 되어야 하지만 보호될 수 없고 embed 요소(element)의 노드 문서샌드박싱 활성화 플래그 설정샌드박스 된 플러그인들 브라우징 컨텍스트 플래그가 설정되는 경우, 유저 에이전트는 플러그인을 인스턴스화 하지 않아야(must)하고, 대신 플러그인이 비활성화 되었음을 전달하는 방법으로 embed 요소(element)를 렌더링해야(must) 합니다. 유저 에이전트는 사용자에게 샌드박스를 재정의하고 그래도 플러그인을 인스턴스화 하기 위한 옵션을 권할 수 있습니다; 사용자가 그러한 옵션을 호출한다면, 유저 에이전트는 위 조건들이 이 요소(element)의 목적에 대해 적용하지 않는 것처럼 수행해야(must) 합니다.

보호될 수 없는 플러그인들은 샌드박스에 의해 부여된 제약사항들을 이행하지 않을 것이기 때문에 (예를 들어, 샌드박스 내 스크립팅이 비활성화 되었을 때 조차 스크립팅을 허용할 수 있습니다) 샌드박스 된 브라우징 컨텍스트들 내에서 비활성화 될 수 있습니다. 유저 에이전트들은 그렇게 하기 위한 옵션이 제공된다면 사용자에게 샌드박스를 재정의하는 것의 위험을 전달해야(should) 합니다.

embed 요소(element)가 중첩된 브라우징 컨텍스트를 나타내는 경우: embed 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로드 후 작업들에 대해 준비되지 않았고, 무엇이든 embed 요소(element)의 브라우징 컨텍스트활성 문서load 이벤트를 지연 시키는 중인 경우, 그리고 embed 요소(element)의 브라우징 컨텍스트load 이벤트들 지연 중 모드에 있는 경우, embed는 그것의 문서의 load 이벤트를 지연시켜야(must) 합니다.

이 섹션에 언급된 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

name, align, hspace, vspace을 제외한 네임스페이스 없는 속성(attribute)은 그것의 이름이 XML 호환 가능하고 대문자 ASCII 문자들을 포함하지 않기만 하면 embed 요소(element)에 명시될 수 있습니다. 이 속성(attribute)들은 이후에 플러그인에 파라미터들로 전달됩니다.

HTML 문서들 내의 모든 속성(attribute)들은 대문자의 제약 사항들이 그 문서에 영향을 주지 않기 때문에 자동으로 소문자로 바뀐 것을 얻습니다.

4개의 예외들은 플러그인에 파라미터들을 전달하는 것을 넘어 부작용을 가지는 레거시 속성(attribute)들을 제외하는 것입니다.

유저 에이전트는 embed가 인스턴스화 될 때, 사용된 플러그인에 대한 네임스페이스를 갖지 않는 embed의 모든 속성(attribute)들의 이름들과 값들을 전달해야(should) 합니다.

요소(element)를 나타내는 HTMLEmbedElement 객체는 embed 요소(element)에 대해 인스턴스화 된 플러그인의 스크립트 가능한 인터페이스가 있다면 이를 노출해야(must) 합니다. 최소한, 이 인터페이스는 레거시 호출 연산을 구현해야(must) 합니다. (이 레거시 호출 연산의 기본 동작은, 예를 들어 기본 플러그인의 레거시 호출자 연산의 동작은, NotSupportedError 예외를 던지는 것이 되도록 제안됩니다.)

embed 요소(element)는 치수 속성(attribute)들을 지원합니다.

IDL 속성(attribute)들 srctype는 각각 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다.

여기 Flash와 같이, 특허 플러그인을 요구하는 리소스를 삽입하는 방법이 있습니다.
<embed src="catgame.swf">

사용자가 플러그인을 가지고 있지 않다면 (예를 들어 플러그인 제공자가 사용자의 플랫폼을 지원하지 않는다며), 사용자는 리소스를 사용하는 것이 불가능할 것입니다.

플러그인에 "high" 값을 가진 "quality" 파라미터를 전달하기 위해, 속성(attribute)이 명시될 수 있습니다:

<embed src="catgame.swf" quality="high">

object 요소(element)를 대신 사용하는 경우, 이것은 다음과 동등할 것입니다:

<object data="catgame.swf">
  <param name="quality" value="high">
</object>

4.7.8. object 요소(element)

카테고리:
흐름(flow) 콘텐트.
어구(phrasing) 콘텐트.
삽입(embedded) 콘텐트.
나열된, 제출 가능한, 다시 연관 시킬 수 있는 양식 관련 요소(element).
분명한(palpable) 콘텐트.
이 요소(element)가 사용될 수 있는 컨텍스트:
삽입(embedded) 콘텐트가 예상되는 곳.
콘텐트 모델:
0개 이상의 param 요소(element)들, 이후, 투명.
text/html에서 태그 생략:
어느 태그도 생략 가능하지 않습니다
콘텐트 속성(attribute)들:
범용 속성(attribute)들
data - 리소스의 주소
type - 삽입된 리소스의 유형
typemustmatch - 사용되는 리소스에 대해 type 속성(attribute)와 Content-Type 값이 일치해야 할 필요가 있는지 여부
name - 중첩된 브라우징 컨텍스트의 이름
form - form 요소(element)와 컨트롤을 연결
width - 가로 치수
height - 세로 치수
허용된 ARIA 역할(role) 속성(attribute) 값들:
application, document 또는 img 또는 presentation.
허용된 ARIA 상태(state)와 속성(property) 속성(attribute)들:
범용 aria-* 속성(attribute)들
허용된 역할(role)들에 적용 가능한 모든 aria-* 속성(attribute)들.
DOM 인터페이스:
interface HTMLObjectElement : HTMLElement {
  attribute DOMString data;
  attribute DOMString type;
  attribute boolean typeMustMatch;
  attribute DOMString name;
  readonly attribute HTMLFormElement? form;
  attribute DOMString width;
  attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  void setCustomValidity(DOMString error);

  legacycaller any (any... arguments);
};
object 요소(element)에 의해 인스턴스화 된 콘텐트의 유형에 따라, 노드도 다른 인터페이스들을 지원합니다.

object 요소(element)는 리소스의 유형에 따라 이미지로, 중첩된 브라우징 컨텍스트로, 또는 플러그인에 의해 처리되는 외부 리소스로 다루어지는 외부 리소스를 나타낼 수 있습니다.

data 속성(attribute)이 존재한다면, 이는 리소스의 주소를 명시합니다. 이 속성(attribute)이 존재한다면, 속성(attribute)은 유효한 잠정적으로 공백으로 둘러 싸일 수 있는 비어있지 않은 URL이어야(must) 합니다.

신뢰하지 않는 다른 출처들로부터의 리소스를 참조하는 작성자들은 아래 정의된 typemustmatch 속성(attribute)을 사용하도록 강력히 권고됩니다. 그 속성(attribute)이 없으면, 작성자가 Flash "allowScriptAccess" 파라미터와 같은 기능을 사용했다 하더라도, 어떤 경우들에서 공격자가 원격 호스트에서 임의의 스크립트를 수행시키기 위한 플러그인 메커니즘을 사용하는 것이 가능합니다.

type 속성(attribute)이 존재한다면, 이 속성(attribute)은 리소스의 유형을 명시합니다. 이 속성(attribute)이 존재한다면, 속성(attribute)은 유효한 MIME 타입이어야(must) 합니다.

적어도 data 속성(attribute)이나 type 속성(attribute) 중 하나는 존재해야(must) 합니다.

typeMustMatch 속성(attribute)은 그 존재가 data 속성(attribute)에 의해 명시된 리소스가 type 속성(attribute)의 값과 앞서 언급된 리소스의 Content-Type과 일치하는 경우에만 사용 됨을 나타내는 불리언 속성(attribute) 입니다.

typemustmatch 속성(attribute)은 data 속성(attribute)과 type 속성(attribute)이 모두 존재하지 않는 한 명시되지 않아야(must) 합니다.

name 속성(attribute)이 존재한다면, 이 속성(attribute)은 유효한 브라우징 컨텍스트 이름이어야(must) 합니다. 주어진 값은 적용 가능하다면, 중첩된 브라우징 컨텍스트를 이름을 붙이는데 사용됩니다.

다음 조건들 중 하나가 발생할 때마다:

...유저 에이전트는 object 요소(element)가 무엇을 나타내는지를 (재)결정하기 위한 다음 단계들을 수행하기 위한 작업을 대기열에 넣어야(must) 합니다. 대기열에 넣어지거나 활발히 수행 중인 이 작업은 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

  1. 사용자가 이 object 요소(element)의 폴백 콘텐트가 요소(element)의 보통의 동작 대신 보여지도록 설정을 지시했다면, 아래 fallback으로 라벨링 된 단계로 건너 뜁니다.

    예를 들어, 콘텐트는 사용자가 더 접근 가능한 것을 찾는 형식을 사용하기 때문에 사용자는 요소(element)의 폴백 콘텐트가 보여지도록 요청할 수 있습니다.

  2. 요소(element)가 후손 미디어 요소(element)를 가지거나, 폴백 콘텐트를 보여주고 있지 않은 후손 object 요소(element)를 가지거나, 요소(element)가 브라우징 컨텍스트를 가진 Document 안에 있지 않거나, 요소(element)의 노드 문서완전히 활성화가 아니거나, 요소(element)가 여전히 HTML 해석기XML 해석기열린 요소(element)들의 스택 안에 있거나, 요소(element)가 렌더링 되는 것이 아니라면, fallback으로 라벨링 된 단계로 건너뜁니다.

  3. classid 속성(attribute)이 존재하고 빈 문자열이 아닌 값을 가진다면: 유저 에이전트가 classid 속성(attribute)의 값에 따라 적절한 플러그인을 찾을 수 있고, 플러그인들이 샌드박스 되지 않는 것이거나 그 플러그인보호될 수 있다면, 그 플러그인사용되어야(should)하고, data 속성(attribute)의 값이 있다면 그것은 플러그인으로 전달되어야(should) 합니다. 적절한 플러그인을 찾을 수 없거나, 플러그인이 오류를 보고한다면, fallback으로 라벨링 된 단계로 점프합니다.

  4. data 속성(attribute)이 존재하고 그 값이 빈 문자열이 아니라면 :
    1. type 속성(attribute)이 존재하고 그 값이 유저 에이전트가 지원하는 유형이 아니며, 유저 에이전트가 그 속성(attribute) 값에 대한 플러그인을 찾을 수 있는 유형이 아니라면, 유저 에이전트는 그것의의 실제 유형을 검사하기 위해 콘텐트를 가져오는(fetch) 것 없이 아래 fallback으로 라벨링 된 단계로 건너뛸 수 있습니다.
    2. data 속성(attribute)에 의해 명시된 URL을 요소(element)에 관련하여 해석 합니다.
    3. 그것이 실패했다면, 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시키고, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.
    4. requestURL결과 URL 문자열이고, 클라이언트가 요소(element)의 노드 문서Window 객체의 환경 설정 객체이며, 목적지가 "unknown"이고, 요소(element)가 브라우징 컨텍스트 범위 출처를 가지지 않는다면 출처 헤더 생략 플래그가 설정되어 있으며, 자격 증명 모드가 "include"이고 URL 자격 증명 사용 플래그가 설정 된 새로운 요청으로 둡니다.
    5. request가져옵니다(fetch).

      리소스를 가져오는(fetch) 것은 리소스가 가져와(fetch)졌을 때 네트워킹 작업 소스에 의해 대기열에 넣어진 작업이 (다음으로 정의된) 수행 될 때까지 요소(element)의 노드 문서load 이벤트를 지연시켜야(must) 합니다.

    6. 리소스가 아직 사용 가능하지 않다면 (예를 들어, 리소스가 캐시에서 아직 사용할 수 없기 때문에, 리소스를 로딩하는 것은 네트워크를 통해 요청을 만드는 것을 요구합니다), 아래 fallback으로 라벨링 된 단계로 건너뜁니다. 리소스가 사용 가능 할 때 네트워킹 작업 소스에 의해 대기열에 넣어진 작업은 이 단계로부터 이 알고리즘을 재시작해야(must) 합니다. 리소스들이 점차적으로 로드될 수 있습니다; 유저 에이전트들은 리소스를 처리하는 것을 시작하기 위해 충분한 데이터라가 얻어질 때마다 리소스를 "사용 가능"한 것으로 간주되도록 선택할 수 있습니다.
    7. 로드가 실패되었다면 (예를 들어, HTTP 404 오류가 있었거나, DNS 오류가 있었거나), 요소(element)에 error라고 이름이 붙은 단순 이벤트를 발생시키고, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.
    8. 다음과 같이, resource type을 결정합니다:

      1. resource type를 알 수 없음으로 둡니다.

      2. object 요소(element)가 type 속성(attribute)과 typemustmatch 속성(attribute)을 가지고, 리소스가 연관된 Content-Type 메타데이터를 가지며, 리소스의 Content-Type 메타데이터에 명시된 유형이 요소(element)의 type 속성(attribute)의 값에 ASCII 대소문자 구분 없이 일치한다면, resource type을 그 유형으로 두고 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      3. object 요소(element)가 typemustmatch 속성(attribute)을 가진다면, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      4. 유저 에이전트가 이 리소스에 대해 Content-Type 헤더들을 엄격히 준수하도록 설정되어 있고, 리소스가 연관된 Content-Type 메타데이터를 가진다면, resource type리소스의 Content-Type 메타데이터 내에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        이것은 사이트가 특정 플러그인을 사용하는 삽입된 리소스를 시도하고 있다는 점에서 취약성을 끌어들일 수 있지만, 원격 사이트는 그것을 무시하고 대신 유저 에이전트에 다른 보안성들을 가진 다른 플러그인을 작동시키는 리소스를 제공합니다.

      5. object 요소(element)에 type 속성(attribute)이 존재하고, 그 속성(attribute)의 값이 유저 에이전트들이 지원하는 유형이 아니라, 플러그인이 지원하는 유형이라면, resource type을 그 type 속성(attribute)에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      6. 다음 목록에서 적절한 단계들의 세트를 수행합니다:

        리소스가 연관된 Content-Type 메타데이터를 가진다면
        1. binary를 false로 둡니다.

        2. 리소스의 Content-Type 메타데이터에 명시된 유형이 "text/plain"이고, 리소스가 텍스트인지 바이너리인지 결정하기 위한 규칙들을 리소스에 적용한 결과가 리소스는 text/plain이 아니다는 것이라면, binary를 true로 설정합니다.

        3. 리소스의 Content-Type 메타데이터에 명시된 유형이 "application/octet-stream"이라면, binary를 true로 설정합니다.

        4. binary가 false라면, resource type리소스의 Content-Type 메타데이터에 명시된 유형으로 두고, 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        5. object 요소(element)에 type 속성(attribute)이 존재하고, 그 값이 application/octet-stream이 아니라면, 다음 단계들을 수행합니다:

          1. 속성(attribute)의 값이 플러그인이 지원하는 유형이거나, 속성(attribute)의 값이 XML MIME 타입이 아닌 "image/"로 시작하는 유형이라면, resource type을 그 type 속성(attribute)에 명시된 유형으로 둡니다.

          2. 아래 handler라고 라벨링 된 단계로 건너뜁니다.

        그렇지 않고, 리소스가 연관된 Content-Type 메타데이터를 가지지 않는다면
        1. object 요소(element)에 type 속성(attribute)이 존재한다면, tentative type을 그 type 속성(attribute)에 명시된 유형으로 둡니다.

          그렇지 않으면, tentative type계산된 리소스의 유형으로 둡니다.

        2. tentative typeapplication/octet-stream아니라면, resource typetentative type로 두고 아래 handler라고 라벨링 된 단계로 건너뜁니다.

      7. URL 해석 알고리즘을 명시된 리소스의 URL에 적용 하는 것이 (다른 리다이렉트들 이후) 경로 컴포넌트가 플러그인이 지원하는 패턴에 일치하는 URL 레코드를 야기한다면, resource type을 그 플러그인이 처리할 수 있는 유형으로 둡니다.

        예를 들어, 플러그인은 네 개 문자열 ".swf"로 끝나는 경로 컴포넌트들을 가진 리소스들을 처리할 수 있다로 말 할 수 있습니다.

      이 단계가 종료되는 것이나, 위 하위 단계들 중 하나가 여전히 알 수 없는 resource type을 가지고 다음 단계로 바로 건너 뛰는 것이 가능합니다. 이 두 경우들에, 다음 단계는 폴백을 작동 시킬 것입니다.

    9. Handler: 다음 경우들의 첫 번째 일치하는 것에 의해 주어진 것으로 콘텐트를 처리합니다:
      resource type이 유저 에이전트가 지원하는 유형이 아니라, 플러그인이 지원하는 유형이라면,

      플러그인들이 샌드박스 되는 것이고 resource type을 지원한는 플러그인이 보호될 수 없다면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      그렇지 않으면, 유저 에이전트는 resource type을 지원하는 플러그인을 사용해야(should) 하고, 그 플러그인에 리소스의 콘텐트를 전달해야(should) 합니다. 플러그인이 오류를 보고한다면, fallback으로 라벨링 된 단계로 건너뜁니다.

      resource typeXML MIME 타입이거나 resource type이 "image/"로 시작하지 않는다면
      object 요소(element)는 새롭게 생성된 중첩된 브라우징 컨텍스트를 이미 가지고 있지 않다면 이와 연관되어야(must) 합니다.

      주어진 리소스의 URLabout:blank가 아니라면, 요소(element)의 중첩된 브라우징 컨텍스트교체 활성화와, 소스 브라우징 컨텍스트로서 object 요소(element)의 노드 문서브라우징 컨텍스트를 가지고 그 리소스로 이동되어야(must) 합니다. (브라우징 컨텍스트가 다른 위치들로 더 이동한다면 object 요소(element)의 data 속성(attribute)은 업데이트 되지 않습니다.)

      주어진 리소스의 URLabout:blank라면, 대신에, 유저 에이전트는 object 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣어야(must) 합니다. load 이벤트는 about:blank 문서 자체에 발생되지 않습니다.

      object 요소(element)는 중첩된 브라우징 컨텍스트를 나타냅니다.

      name 속성(attribute)이 존재한다면, 브라우징 컨텍스트 이름은 이 속성(attribute)의 값으로 설정 되어야(must) 합니다; 그렇지 않으면, 브라우징 컨텍스트 이름은 빈 문자열로 설정 되어야(must) 합니다.

      resource type이 "image/"로 시작하고, 이미지에 대한 지원이 비활성화되지 않았다면

      이미지 스니핑 규칙을 이미지의 유형을 결정하는데 적용합니다.

      object 요소(element)는 명시된 이미지를 나타냅니다. 이미지는 중첩된 브라우징 컨텍스트가 아닙니다.

      이미지가 렌더링 될 수 없다면, 예를 들어 그것이 잘못되었거나 지원되지 않는 형식이라면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      그렇지 않으면

      주어진 resource type은 지원되지 않습니다. 아래 fallback으로 라벨링 된 단계로 건너뜁니다.

      앞선 단계가 알 수 없는 것이 되는 resource type으로 끝났다면, 이것은 작동 된 경우입니다.

    10. 요소(element)의 콘텐트는 object 요소(element)가 나타내는 것의 일부가 아닙니다.
    11. 이 단계들을 중단시킵니다. 리소스가 완전히 로드되었을 때, 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.

  5. data 속성(attribute)이 없지만 type 속성(attribute)이 존재하고, 유저 에이전트가 type 속성(attribute)의 값에 따라 적절한 플러그인을 찾을 수 있고, 플러그인들이 샌드박스 되는 것이 아니거나 플러그인보호될 수 있다면, 그 플러그인사용되어야(should) 합니다. 이 조건을 만나지 못하거나, 플러그인이 오류를 보고한다면, 아래 fallback으로 라벨링 된 단계로 건너뜁니다. 그렇지 않으면 이 단계들을 중단합니다; 플러그인이 완전히 로드될 때, 요소(element)에 load라고 이름이 붙은 단순 이벤트를 발생시키기 위한 작업을 대기열에 넣습니다.
  6. Fallback: object 요소(element)는 다른 선두의 자식 param 요소(element)들을 무시하고, 요소(element)의 자식을 나타냅니다. 이것이 요소(element)의 폴백 콘텐트입니다. 요소(element)가 인스턴스화 된 플러그인을 가진다면, 그것은 언로드 됩니다.

위 알고리즘이 플러그인을 인스턴스화 할 때, 유저 에이전트는 요소(element)의 사용된 모든 모든 속성(attribute)들의 이름들과 값들을, 그것들이 요소(element)에 추가된 순서에 따라, 소스 순서에 따라 정렬되는 해석기 의해 추가된 속성(attribute)들, 그 뒤로 값이 null인 "PARAM"으로 이름이 붙은 파라미터, 그 뒤로 object 요소(element)의 자식인 param 요소(element)에 의해 주어진 파라미터들의 모든 이름들과 값들을 트리 순서에 따라 플러그인에 전달해야(should) 합니다. 플러그인이 스트립트 가능한 인터페이스를 지원한다면, 요소(element)를 나타내는 HTMLObjectElement 객체는 그 인터페이스를 노출해야(should) 합니다. object 요소(element)는 플러그인나타냅니다. 플러그인은 중첩된 브라우징 컨텍스트가 아닙니다.

object 요소(element)의 노드 문서샌드박싱 활성화 플래그 설정샌드박스 된 플러그인 브라우징 컨텍스트 플래그가 설정 되었다면 플러그인들은 object 요소(element)의 목적을 위해 샌드박스 된 것으로 간주됩니다.

위 알고리즘 때문에, object 요소(element)들의 콘텐츠는 참조된 리소스들이 보여질 수 없을 때에만 (예를 들어, 그것이 404 오류를 반환했기 때문에) 사용되는 폴백 콘텐트로서 동작합니다. 이것은 다른 능력들을 가진 여러 유저 에이전트들을 타게팅하여, 유저 에이전트가 지원하는 처음 것을 선택하도록 여러 object 요소(element)들이 서로의 내부에 중첩되는 것을 허용합니다.

object 요소(element)가 중첩된 브라우징 컨텍스트를 나타내는 경우: object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서로드 후 작업들에 대해 준비되지 않고, 어떤 것이든 object 요소(element)의 브라우징 컨텍스트활성 문서load 이벤트를 지원시키고 있는 경우와, object 요소(element)의 브라우징 컨텍스트load 이벤트들 지연 중 모드에 있다면, object는 그것의 문서의 load 이벤트를 지연시켜야(must) 합니다.

이 섹션에 언급된 작업들에 대한 작업 소스DOM 조작 작업 소스입니다.

name 속성(attribute)이 설정될 때마다, object 요소(element)가 중첩된 브라우징 컨텍스트를 가진다면, 그것의 이름은 새로운 값으로 변경되어야(must) 합니다. 속성(attribute)이 제거된다면, object 요소(element)가 브라우징 컨텍스트를 가진다면, 브라우징 컨텍스트 이름은 빈 문자열로 설정 되어야(must) 합니다.

form 속성(attribute)은 object 요소(element)를 그것의 양식 소유자와 명시적으로 연관시키기 위해 사용됩니다.

제약조건 확인: object 요소(element)들은 항상 제약 조건 확인을 금지됩니다.

object 요소(element)는 치수 속성(attribute)들을 지원합니다.

IDL 속성(attribute)들 data, type, name은 각각 동일한 이름의 각 콘텐트 속성(attribute)들을 반영해야(must) 합니다. typeMustMatch IDL 속성(attribute)은 typemustmatch 콘텐트 속성(attribute)을 반영해야 합니다. useMap IDL 속성은 usemap 콘텐트 속성을 반영해야(must) 합니다.

contentDocument IDL 속성(attribute)은 object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서Document 객체가 존재하고 그것의 출처현직 설정 객체에 의해 명시된 출처로서 동일 출처 도메인이라면 object 요소(element)의 중첩된 브라우징 컨텍스트활성 문서Document 객체를 반환해야(must) 하고, 그렇지 않으면 null을 반환해야(must) 합니다.

contentWindow IDL 속성(attribute)은 object 요소(element)의 중첩된 브라우징 컨텍스트WindowProxy 객체를 가진다면 이를 반환해야(must) 하고 그렇지 않으면 null을 반환해야(must) 합니다.

willValidate, validity, validationMessage 속성(attribute)들과 checkValidity(), reportValidity(), setCustomValidity() 메서드들은 제약 조건 확인 API의 일부입니다. form IDL 속성(attribute)은 요소(element)의 forms API의 일부입니다.

모든 object 요소(element)는 레거시 호출자 연산을 가집니다. object 요소(element)가 레거시 호출자 연산을 정의하는 스크립트 가능한 인터페이스를 지원하는 인스턴스화 된 플러그인을 가진다면, 그것은 객체의 레거시 호출자 연산의 동작이어야(must) 합니다. 그렇지 않으면, 객체의 레거시 호출자 연산은 NotSupportedError 예외를 던져야(must) 합니다.

다음 예에서, 자바 애플릿은 object 요소(element)를 사용하여 페이지에 삽입됩니다. (일반적으로 말해서, 이것들과 같은 애플릿들을 사용하는 것은 피하고 대신 기능성을 제공하기 위해 네이티브 JavaScript와 HTML을 사용하는 것이, 어플리케이션이 서드 파티 플러그인을 요구하지 않고 모든 웹 브라우저들에서 동작할 것이기 때문에, 더 좋습니다. 많은 기기들, 특히 임베디드 기기는 Java와 같은 서드 파티 기술을 지원하지 않습니다.)
<figure>
  <object type="application/x-java-applet">
  <param name="code" value="MyJavaClass">
  <p>You do not have Java available, or it is disabled.</p>
  </object>
  <figcaption>My Java Clock</figcaption>
</figure>
이 예에서, HTML 페이지는 object 요소(element)를 사용하여 다른 HTML에 삽입됩니다.
<figure>
  <object data="clock.html"></object>
  <figcaption>My HTML Clock</figcaption>
</figure>
다음 예는 HTML에 플러그인이 어떻게 사용될 수 있는지를 (이 경우 비디오 파일을 보여주기 위한 플래시 플러그인) 보여줍니다. 폴백은 활성화 된 Flash를 가지지 않은 사용자들에 대해, 이 경우에 비디오를 보여주기 위해 video를 지원하는 유저 에이전트들을 사용하는 사용자에 대해서는 video 요소(element)를 사용하고, 마지막으로 플래시나 video-가능 브라우저를 가지지 않은 사용자들에 대해서는 비디오로의 링크를 제공하여 제공됩니다.
<p>Look at my video:
  <object type="application/x-shockwave-flash">
  <param name=movie value="https://video.example.com/library/watch.swf">
  <param name=allowfullscreen value=true>
  <param name=flashvars value="https://video.example.com/vids/315981">
  <video controls src="https://video.example.com/vids/315981">
    <a href="https://video.example.com/vids/315981">View video</a>.
  </video>
  </object>
</p>

4.7.9. The param element

Categories:
None.
Contexts in which this element can be used:
As a child of an object element, before any flow content.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
name - Name of parameter
value - Value of parameter
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLParamElement : HTMLElement {
  attribute DOMString name;
  attribute DOMString value;
};

The param element defines parameters for plugins invoked by object elements. It does not represent anything on its own.

The name attribute gives the name of the parameter.

The value attribute gives the value of the parameter.

Both attributes must be present. They may have any value.

If both attributes are present, and if the parent element of the param is an object element, then the element defines a parameter with the given name-value pair.

If either the name or value of a parameter defined by a param element that is the child of an object element that represents an instantiated plugin changes, and if that plugin is communicating with the user agent using an API that features the ability to update the plugin when the name or value of a parameter so changes, then the user agent must appropriately exercise that ability to notify the plugin of the change.

The IDL attributes name and value must both reflect the respective content attributes of the same name.

The following example shows how the param element can be used to pass a parameter to a plugin, in this case the O3D plugin.
<!DOCTYPE HTML>
<html lang="en">
  <head>
    <title>O3D Utah Teapot</title>
  </head>
  <body>
    <p>
    <object type="application/vnd.o3d.auto">
      <param name="o3d_features" value="FloatingPointTextures">
      <img src="o3d-teapot.png"
          title="3D Utah Teapot illustration rendered using O3D."
          alt="When O3D renders the Utah Teapot, it appears as a squat
          teapot with a shiny metallic finish on which the
          surroundings are reflected, with a faint shadow caused by
          the lighting.">
      <p>To see the teapot actually rendered by O3D on your
      computer, please download and install the <a
      href="https://code.google.com/apis/o3d/docs/gettingstarted.html#install">O3D plugin</a>.</p>
    </object>
    <script src="o3d-teapot.js"></script>
    </p>
  </body>
</html>

4.7.10. The video element

Categories:
Flow content.
Phrasing content.
Embedded content.
If the element has a controls attribute: interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
If the element has a src attribute: zero or more track elements, then transparent, but with no media element descendants.
If the element does not have a src attribute: zero or more source elements, then zero or more track elements, then transparent, but with no media element descendants.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
src - Address of the resource
crossorigin - How the element handles crossorigin requests
poster - Poster frame to show prior to video playback
preload - Hints how much buffering the media resource will likely need
autoplay - Hint that the media resource can be started automatically when the page is loaded
loop - Whether to loop the media resource
muted - Whether to mute the media resource by default
controls - Show user agent controls
width - Horizontal dimension
height - Vertical dimension
Allowed ARIA role attribute values:
application.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLVideoElement : HTMLMediaElement {
  attribute unsigned long width;
  attribute unsigned long height;
  readonly attribute unsigned long videoWidth;
  readonly attribute unsigned long videoHeight;
  attribute DOMString poster;
};

A video element is used for playing videos or movies, and audio files with captions.

Content may be provided inside the video element. User agents should not show this content to the user; it is intended for older Web browsers which do not support video, so that legacy video plugins can be tried, or to show text to the users of these older browsers informing them of how to access the video contents.

In particular, this content is not intended to address accessibility concerns. To make video content accessible to the partially sighted, the blind, the hard-of-hearing, the deaf, and those with other physical or cognitive disabilities, a variety of features are available. Captions can be provided, either embedded in the video stream or as external files using the track element. Sign-language tracks can be provided, again either embedded in the video stream. Audio descriptions can be provided, either as a separate track embedded in the video stream, or in text form using a WebVTT file referenced using the track element and synthesized into speech by the user agent. WebVTT can also be used to provide chapter titles. For users who would rather not use a media element at all, transcripts or other textual alternatives can be provided by simply linking to them in the prose near the video element. [WEBVTT]

The video element is a media element whose media data is ostensibly video data, possibly with associated audio data.

The src, preload, autoplay, loop, muted, and controls attributes are the attributes common to all media elements.

The poster content attribute gives the address of an image file that the user agent can show while no video data is available. The attribute, if present, must contain a valid non-empty URL potentially surrounded by spaces.

If the specified resource is to be used, then, when the element is created or when the poster attribute is set, changed, or removed, the user agent must run the following steps to determine the element’s poster frame (regardless of the value of the element’s show poster flag):

  1. If there is an existing instance of this algorithm running for this video element, abort that instance of this algorithm without changing the poster frame.
  2. If the poster attribute’s value is the empty string or if the attribute is absent, then there is no poster frame; abort these steps.
  3. Parse the poster attribute’s value relative to the element. If this fails, then there is no poster frame; abort these steps.
  4. Let request be a new request whose URL is the resulting URL string, client is the element’s node document’s Window object’s environment settings object, type is "image", destination is "subresource", credentials mode is "include", and whose use-URL-credentials flag is set.
  5. Fetch request. This must delay the load event of the element’s node document.
  6. If an image is thus obtained, the poster frame is that image. Otherwise, there is no poster frame.

The image given by the poster attribute, the poster frame, is intended to be a representative frame of the video (typically one of the first non-blank frames) that gives the user an idea of what the video is like.


A video element represents what is given for the first matching condition in the list below:

When no video data is available (the element’s readyState attribute is either HAVE_NOTHING, or HAVE_METADATA but no video data has yet been obtained at all, or the element’s readyState attribute is any subsequent value but the media resource does not have a video channel)
The video element represents its poster frame, if any, or else transparent black with no intrinsic dimensions.
When the video element is paused, the current playback position is the first frame of video, and the element’s show poster flag is set
The video element represents its poster frame, if any, or else the first frame of the video.
When the video element is paused, and the frame of video corresponding to the current playback position is not available (e.g., because the video is seeking or buffering)
When the video element is neither potentially playing nor paused (e.g., when seeking or stalled)
The video element represents the last frame of the video to have been rendered.
When the video element is paused
The video element represents the frame of video corresponding to the current playback position.
Otherwise (the video element has a video channel and is potentially playing)
The video element represents the frame of video at the continuously increasing "current" position. When the current playback position changes such that the last frame rendered is no longer the frame corresponding to the current playback position in the video, the new frame must be rendered.

Frames of video must be obtained from the video track that was selected when the event loop last reached step 1.

Which frame in a video stream corresponds to a particular playback position is defined by the video stream’s format.

The video element also represents any text track cues whose text track cue active flag is set and whose text track is in the showing mode, and any audio from the media resource, at the current playback position.

Any audio associated with the media resource must, if played, be played synchronized with the current playback position, at the element’s effective media volume. The user agent must play the audio from audio tracks that were enabled when the event loop last reached step 1.

In addition to the above, the user agent may provide messages to the user (such as "buffering", "no video loaded", "error", or more detailed information) by overlaying text or icons on the video or other areas of the element’s playback area, or in another appropriate manner.

User agents that cannot render the video may instead make the element represent a link to an external video playback utility or to the video data itself.

When a video element’s media resource has a video channel, the element provides a paint source whose width is the media resource’s intrinsic width, whose height is the media resource’s intrinsic height, and whose appearance is the frame of video corresponding to the current playback position, if that is available, or else (e.g., when the video is seeking or buffering) its previous appearance, if any, or else (e.g., because the video is still loading the first frame) blackness.


video . videoWidth
video . videoHeight

These attributes return the intrinsic dimensions of the video, or zero if the dimensions are not known.

The intrinsic width and intrinsic height of the media resource are the dimensions of the resource in CSS pixels after taking into account the resource’s dimensions, aspect ratio, clean aperture, resolution, and so forth, as defined for the format used by the resource. If an anamorphic format does not define how to apply the aspect ratio to the video data’s dimensions to obtain the "correct" dimensions, then the user agent must apply the ratio by increasing one dimension and leaving the other unchanged.

The videoWidth IDL attribute must return the intrinsic width of the video in CSS pixels. The videoHeight IDL attribute must return the intrinsic height of the video in CSS pixels. If the element’s readyState attribute is HAVE_NOTHING, then the attributes must return 0.

Whenever the intrinsic width or intrinsic height of the video changes (including, for example, because the selected video track was changed), if the element’s readyState attribute is not HAVE_NOTHING, the user agent must queue a task to fire a simple event named resize at the media element.

The video element supports dimension attributes.

In the absence of style rules to the contrary, video content should be rendered inside the element’s playback area such that the video content is shown centered in the playback area at the largest possible size that fits completely within it, with the video content’s aspect ratio being preserved. Thus, if the aspect ratio of the playback area does not match the aspect ratio of the video, the video will be shown letterboxed or pillarboxed. Areas of the element’s playback area that do not contain the video represent nothing.

In user agents that implement CSS, the above requirement can be implemented by using the style rule suggested in §10 Rendering.

The intrinsic width of a video element’s playback area is the intrinsic width of the poster frame, if that is available and the element currently represents its poster frame; otherwise, it is the intrinsic width of the video resource, if that is available; otherwise the intrinsic width is missing.

The intrinsic height of a video element’s playback area is the intrinsic height of the poster frame, if that is available and the element currently represents its poster frame; otherwise it is the intrinsic height of the video resource, if that is available; otherwise the intrinsic height is missing.

The default object size is a width of 300 CSS pixels and a height of 150 CSS pixels. [CSS3-IMAGES]


User agents should provide controls to enable or disable the display of closed captions, audio description tracks, and other additional data associated with the video stream, though such features should, again, not interfere with the page’s normal rendering.

User agents may allow users to view the video content in manners more suitable to the user (e.g., fullscreen or in an independent resizable window). As for the other user interface features, controls to enable this should not interfere with the page’s normal rendering unless the user agent is exposing a user interface. In such an independent context, however, user agents may make full user interfaces visible even if the controls attribute is absent.

User agents may allow video playback to affect system features that could interfere with the user’s experience; for example, user agents could disable screensavers while video playback is in progress.


The poster IDL attribute must reflect the poster content attribute.

This example shows how to detect when a video has failed to play correctly:
<script>
  function failed(e) {
    // video playback failed - show a message saying why
    switch (e.target.error.code) {
      case e.target.error.MEDIA_ERR_ABORTED:
        alert('You aborted the video playback.');
        break;
      case e.target.error.MEDIA_ERR_NETWORK:
        alert('A network error caused the video download to fail part-way.');
        break;
      case e.target.error.MEDIA_ERR_DECODE:
        alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
        break;
      case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
        alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
        break;
      default:
        alert('An unknown error occurred.');
        break;
    }
  }
</script>
<p><video src="tgif.vid" autoplay controls onerror="failed(event)"></video></p>
<p><a href="tgif.vid">Download the video file</a>.</p>

4.7.11. The audio element

Categories:
Flow content.
Phrasing content.
Embedded content.
If the element has a controls attribute: Interactive content.
If the element has a controls attribute: Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
If the element has a src attribute: zero or more track elements, then transparent, but with no media element descendants.
If the element does not have a src attribute: zero or more source elements, then zero or more track elements, then transparent, but with no media element descendants.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
src - Address of the resource
crossorigin - How the element handles crossorigin requests
preload - Hints how much buffering the media resource will likely need
autoplay - Hint that the media resource can be started automatically when the page is loaded
loop - Whether to loop the media resource
muted - Whether to mute the media resource by default
controls - Show user agent controls
Allowed ARIA role attribute values:
application.
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
[NamedConstructor=Audio(optional DOMString src)]
interface HTMLAudioElement : HTMLMediaElement {};

An audio element represents a sound or audio stream.

Content may be provided inside the audio element. User agents should not show this content to the user; it is intended for older Web browsers which do not support audio, so that legacy audio plugins can be tried, or to show text to the users of these older browsers informing them of how to access the audio contents.

In particular, this content is not intended to address accessibility concerns. To make audio content accessible to the deaf or to those with other physical or cognitive disabilities, a variety of features are available. If captions or a sign language video are available, the video element can be used instead of the audio element to play the audio, allowing users to enable the visual alternatives. Chapter titles can be provided to aid navigation, using the track element and a WebVTT file. And, naturally, transcripts or other textual alternatives can be provided by simply linking to them in the prose near the audio element. [WEBVTT]

The audio element is a media element whose media data is ostensibly audio data.

The src, preload, autoplay, loop, muted, and controls attributes are the attributes common to all media elements.

When an audio element is potentially playing, it must have its audio data played synchronized with the current playback position, at the element’s effective media volume. The user agent must play the audio from audio tracks that were enabled when the event loop last reached step 1.

When an audio element is not potentially playing, audio must not play for the element.

audio = new Audio( [ url ] )

Returns a new audio element, with the src attribute set to the value passed in the argument, if applicable.

A constructor is provided for creating HTMLAudioElement objects (in addition to the factory methods from DOM such as createElement()): Audio(src). When invoked as a constructor, it must return a new HTMLAudioElement object (a new audio element). The element must be created with its preload attribute set to the literal value "auto". If the src argument is present, the object created must be created with its src content attribute set to the provided value (this will cause the user agent to invoke the object’s resource selection algorithm before returning). The element’s node document must be the active document of the browsing context of the Window object on which the interface object of the invoked constructor is found.

4.7.12. The source element

Categories:
None.
Contexts in which this element can be used:
As a child of a media element, before any flow content or track elements.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
src - Address of the resource
type - Type of embedded resource
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLSourceElement : HTMLElement {
  attribute DOMString src;
  attribute DOMString type;
};

The source element allows authors to specify multiple alternative media resources for media elements. It does not represent anything on its own.

The src attribute gives the address of the media resource. The value must be a valid non-empty URL potentially surrounded by spaces. This attribute must be present.

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

The type content attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. If specified, its value must be a valid MIME type. The codecs parameter, which certain MIME types define, might be necessary to specify exactly how the resource is encoded. [RFC6381]

The following list shows some examples of how to use the codecs= MIME parameter in the type attribute.
H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
    
H.264 Extended profile video (baseline-compatible) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'>
    
H.264 Main profile video level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
    
H.264 "High" profile video (incompatible with main, baseline, or extended profiles) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.64001E, mp4a.40.2"'>
    
MPEG-4 Visual Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.8, mp4a.40.2"'>
    
MPEG-4 Advanced Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.240, mp4a.40.2"'>
    
MPEG-4 Visual Simple Profile Level 0 video and AMR audio in 3GPP container
<source src='video.3gp' type='video/3gpp; codecs="mp4v.20.8, samr"'>
    
Theora video and Vorbis audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'>
    
Theora video and Speex audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="theora, speex"'>
    
Vorbis audio alone in Ogg container
<source src='audio.ogg' type='audio/ogg; codecs=vorbis'>
    
Speex audio alone in Ogg container
<source src='audio.spx' type='audio/ogg; codecs=speex'>
    
FLAC audio alone in Ogg container
<source src='audio.oga' type='audio/ogg; codecs=flac'>
    
Dirac video and Vorbis audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="dirac, vorbis"'>
    

If a source element is inserted as a child of a media element that has no src attribute and whose networkState has the value NETWORK_EMPTY, the user agent must invoke the media element’s resource selection algorithm.

The IDL attributes src and type must reflect the respective content attributes of the same name.

If the author isn’t sure if user agents will all be able to render the media resources provided, the author can listen to the error event on the last source element and trigger fallback behavior:
<script>
  function fallback(video) {
    // replace <video> with its contents
    while (video.hasChildNodes()) {
      if (video.firstChild instanceof HTMLSourceElement)
        video.removeChild(video.firstChild);
      else
        video.parentNode.insertBefore(video.firstChild, video);
    }
    video.parentNode.removeChild(video);
  }
</script>
<video controls autoplay>
  <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'
          onerror="fallback(parentNode)">
  ...
</video>

4.7.13. The track element

Categories:
None.
Contexts in which this element can be used:
As a child of a media element, before any flow content.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
kind - The type of text track
src - Address of the resource
srclang - Language of the text track
label - User-visible label
default - Enable the track if no other text track is more suitable
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLTrackElement : HTMLElement {
  attribute DOMString kind;
  attribute DOMString src;
  attribute DOMString srclang;
  attribute DOMString label;
  attribute boolean default;

  const unsigned short NONE = 0;
  const unsigned short LOADING = 1;
  const unsigned short LOADED = 2;
  const unsigned short ERROR = 3;
  readonly attribute unsigned short readyState;

  readonly attribute TextTrack track;
};

The track element allows authors to specify explicit external text resources for media elements. It does not represent anything on its own.

The kind attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The keyword given in the first cell of each row maps to the state given in the second cell.

Keyword State Brief description
subtitles Subtitles Transcription or translation of the dialog, suitable for when the sound is available but not understood (e.g., because the user does not understand the language of the media resource’s audio track). Overlaid on the video.
captions Captions Transcription or translation of the dialog, sound effects, relevant musical cues, and other relevant audio information, suitable for when sound is unavailable or not clearly audible (e.g., because it is muted, drowned-out by ambient noise, or because the user is deaf). Overlaid on the video; labeled as appropriate for the hard-of-hearing.
descriptions Descriptions Textual descriptions of the video component of the media resource, intended for audio synthesis when the visual component is obscured, unavailable, or not usable (e.g., because the user is interacting with the application without a screen while driving, or because the user is blind). Synthesized as audio.
chapters Chapters Chapter titles, intended to be used for navigating the media resource. Displayed as an interactive (potentially nested) list in the user agent’s interface.
metadata Metadata Tracks intended for use from script. Not displayed by the user agent.

The attribute may be omitted. The missing value default is the subtitles state. The invalid value default is the metadata state.

The src attribute gives the address of the text track data. The value must be a valid non-empty URL potentially surrounded by spaces. This attribute must be present.

If the element has a src attribute whose value is not the empty string and whose value, when the attribute was set, could be successfully parsed relative to the element’s node document, then the element’s track URL is the resulting URL string. Otherwise, the element’s track URL is the empty string.

If the element’s track URL identifies a WebVTT resource, and the element’s kind attribute is not in the Metadata state, then the WebVTT file must be a WebVTT file using cue text. [WEBVTT]

Furthermore, if the element’s track URL identifies a WebVTT resource, and the element’s kind attribute is in the chapters state, then the WebVTT file must be both a WebVTT file using chapter title text and a WebVTT file using only nested cues. [WEBVTT]

The srclang attribute gives the language of the text track data. The value must be a valid BCP 47 language tag. This attribute must be present if the element’s kind attribute is in the subtitles state. [BCP47]

If the element has a srclang attribute whose value is not the empty string, then the element’s track language is the value of the attribute. Otherwise, the element has no track language.

The label attribute gives a user-readable title for the track. This title is used by user agents when listing subtitle, caption, and audio description tracks in their user interface.

The value of the label attribute, if the attribute is present, must not be the empty string. Furthermore, there must not be two track element children of the same media element whose kind attributes are in the same state, whose srclang attributes are both missing or have values that represent the same language, and whose label attributes are again both missing or both have the same value.

If the element has a label attribute whose value is not the empty string, then the element’s track label is the value of the attribute. Otherwise, the element’s track label is an empty string.

The default attribute is a boolean attribute, which, if specified, indicates that the track is to be enabled if the user’s preferences do not indicate that another track would be more appropriate.

Each media element must have no more than one track element child whose kind attribute is in the Subtitles or Captions state and whose default attribute is specified.

Each media element must have no more than one track element child whose kind attribute is in the Descriptions state and whose default attribute is specified.

Each media element must have no more than one track element child whose kind attribute is in the Chapters state and whose default attribute is specified.

There is no limit on the number of track elements whose kind attribute is in the Metadata state and whose default attribute is specified.

track . readyState
Returns the text track readiness state, represented by a number from the following list:
track . NONE (0)
The text track not loaded state.
track . LOADING (1)
The text track loading state.
track . LOADED (2)
The text track loaded state.
track . ERROR (3)
The text track failed to load state.
track . track

Returns the TextTrack object corresponding to the text track of the track element.

The readyState attribute must return the numeric value corresponding to the text track readiness state of the track element’s text track, as defined by the following list:

NONE (numeric value 0)
The text track not loaded state.
LOADING (numeric value 1)
The text track loading state.
LOADED (numeric value 2)
The text track loaded state.
ERROR (numeric value 3)
The text track failed to load state.

The track IDL attribute must, on getting, return the track element’s text track’s corresponding TextTrack object.

The src, srclang, label, and default IDL attributes must reflect the respective content attributes of the same name. The kind IDL attribute must reflect the content attribute of the same name, limited to only known values.

This video has subtitles in several languages:
<video src="brave.webm">
  <track kind=subtitles src=brave.en.vtt srclang=en label="English">
  <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing">
  <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Français">
  <track kind=subtitles src=brave.de.vtt srclang=de lang=de label="Deutsch">
</video>

(The lang attributes on the last two describe the language of the label attribute, not the language of the subtitles themselves. The language of the subtitles is given by the srclang attribute.)

4.7.14. Media elements

HTMLMediaElement objects (audio and video, in this specification) are simply known as media elements.

enum CanPlayTypeResult { "" /* empty string */, "maybe", "probably" };
typedef (MediaStream or MediaSource or Blob) MediaProvider;
interface HTMLMediaElement : HTMLElement {

  // error state
  readonly attribute MediaError? error;

  // network state
  attribute DOMString src;
  attribute MediaProvider? srcObject;
  readonly attribute DOMString currentSrc;
  attribute DOMString? crossOrigin;
  const unsigned short NETWORK_EMPTY = 0;
  const unsigned short NETWORK_IDLE = 1;
  const unsigned short NETWORK_LOADING = 2;
  const unsigned short NETWORK_NO_SOURCE = 3;
  readonly attribute unsigned short networkState;
  attribute DOMString preload;
  readonly attribute TimeRanges buffered;
  void load();
  CanPlayTypeResult canPlayType(DOMString type);

  // ready state
  const unsigned short HAVE_NOTHING = 0;
  const unsigned short HAVE_METADATA = 1;
  const unsigned short HAVE_CURRENT_DATA = 2;
  const unsigned short HAVE_FUTURE_DATA = 3;
  const unsigned short HAVE_ENOUGH_DATA = 4;
  readonly attribute unsigned short readyState;
  readonly attribute boolean seeking;

  // playback state
  attribute double currentTime;
  void fastSeek(double time);
  readonly attribute unrestricted double duration;
  object getStartDate();
  readonly attribute boolean paused;
  attribute double defaultPlaybackRate;
  attribute double playbackRate;
  readonly attribute TimeRanges played;
  readonly attribute TimeRanges seekable;
  readonly attribute boolean ended;
  attribute boolean autoplay;
  attribute boolean loop;
  void play();
  void pause();

  // controls
  attribute boolean controls;
  attribute double volume;
  attribute boolean muted;
  attribute boolean defaultMuted;

  // tracks
  [SameObject] readonly attribute AudioTrackList audioTracks;
  [SameObject] readonly attribute VideoTrackList videoTracks;
  [SameObject] readonly attribute TextTrackList textTracks;
  TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
};

The media element attributes, src, crossorigin, preload, autoplay, loop, muted, and controls, apply to all media elements. They are defined in this section.

Media elements are used to present audio data, or video and audio data, to the user. This is referred to as media data in this section, since this section applies equally to media elements for audio or for video.

The term media resource is used to refer to the complete set of media data, e.g., the complete video file, or complete audio file.

A media resource can have multiple audio and video tracks. For the purposes of a media element, the video data of the media resource is only that of the currently selected track (if any) as given by the element’s videoTracks attribute when the event loop last reached step 1, and the audio data of the media resource is the result of mixing all the currently enabled tracks (if any) given by the element’s audioTracks attribute when the event loop last reached step 1.

Both audio and video elements can be used for both audio and video. The main difference between the two is simply that the audio element has no playback area for visual content (such as video or captions), whereas the video element does.

Except where otherwise explicitly specified, the task source for all the tasks queued in this section and its subsections is the media element event task source of the media element in question.

4.7.14.1. Error codes
media . error

Returns a MediaError object representing the current error state of the element.

Returns null if there is no error.

All media elements have an associated error status, which records the last error the element encountered since its resource selection algorithm was last invoked. The error attribute, on getting, must return the MediaError object created for this last error, or null if there has not been an error.

interface MediaError {
  const unsigned short MEDIA_ERR_ABORTED = 1;
  const unsigned short MEDIA_ERR_NETWORK = 2;
  const unsigned short MEDIA_ERR_DECODE = 3;
  const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;
  readonly attribute unsigned short code;
};
media . error . code

Returns the current error’s error code, from the list below.

The code attribute of a MediaError object must return the code for the error, which must be one of the following:

MEDIA_ERR_ABORTED (numeric value 1)
The fetching process for the media resource was aborted by the user agent at the user’s request.
MEDIA_ERR_NETWORK (numeric value 2)
A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.
MEDIA_ERR_DECODE (numeric value 3)
An error of some description occurred while decoding the media resource, after the resource was established to be usable.
MEDIA_ERR_SRC_NOT_SUPPORTED (numeric value 4)
The media resource indicated by the src attribute or assigned media provider object was not suitable.
4.7.14.2. Location of the media resource

The src content attribute on media elements gives the address of the media resource (video, audio) to show. The attribute, if present, must contain a valid non-empty URL potentially surrounded by spaces.

The crossorigin content attribute on media elements is a CORS settings attribute.

If a media element is created with a src attribute, the user agent must immediately invoke the media element’s resource selection algorithm.

If a src attribute of a media element is set or changed, the user agent must invoke the media element’s media element load algorithm. (Removing the src attribute does not do this, even if there are source elements present.)

The src IDL attribute on media elements must reflect the content attribute of the same name.

The crossOrigin IDL attribute must reflect the crossorigin content attribute.

A media provider object is an object that can represent a media resource, separate from a URL. MediaStream objects, MediaSource objects, Blob objects, and File objects are all media provider objects.

Each media element can have an assigned media provider object, which is a media provider object. When a media element is created, it has no assigned media provider object.

media . srcObject [ = source ]
Allows the media element to be assigned a media provider object.
media . currentSrc
Returns the URL of the current media resource, if any.

Returns the empty string when there is no media resource, or it doesn’t have a URL.

The currentSrc IDL attribute is initially the empty string. Its value is changed by the resource selection algorithm defined below.

The srcObject IDL attribute, on getting, must return the element’s assigned media provider object, if any, or null otherwise. On setting, it must set the element’s assigned media provider object to the new value, and then invoke the element’s media element load algorithm.

There are three ways to specify a media resource, the srcObject IDL attribute, the src content attribute, and source elements. The IDL attribute takes priority, followed by the content attribute, followed by the elements.

4.7.14.3. MIME types

A media resource can be described in terms of its type, specifically a MIME type, in some cases with a codecs parameter. (Whether the codecs parameter is allowed or not depends on the MIME type.) [RFC6381]

Types are usually somewhat incomplete descriptions; for example "video/mpeg" doesn’t say anything except what the container type is, and even a type like "video/mp4; codecs="avc1.42E01E, mp4a.40.2"" doesn’t include information like the actual bitrate (only the maximum bitrate). Thus, given a type, a user agent can often only know whether it might be able to play media of that type (with varying levels of confidence), or whether it definitely cannot play media of that type.

A type that the user agent knows it cannot render is one that describes a resource that the user agent definitely does not support, for example because it doesn’t recognize the container type, or it doesn’t support the listed codecs.

The MIME type "application/octet-stream" with no parameters is never a type that the user agent knows it cannot render. User agents must treat that type as equivalent to the lack of any explicit Content-Type metadata when it is used to label a potential media resource.

Only the MIME type "application/octet-stream" with no parameters is special-cased here; if any parameter appears with it, it will be treated just like any other MIME type. This is a deviation from the rule that unknown MIME type parameters should be ignored.

media . canPlayType(type)

Returns the empty string (a negative response), "maybe", or "probably" based on how confident the user agent is that it can play media resources of the given type.

The canPlayType(type) method must return the empty string if type is a type that the user agent knows it cannot render or is the type "application/octet-stream"; it must return "probably" if the user agent is confident that the type represents a media resource that it can render if used in with this audio or video element; and it must return "maybe" otherwise. Implementors are encouraged to return "maybe" unless the type can be confidently established as being supported or not. Generally, a user agent should never return "probably" for a type that allows the codecs parameter if that parameter is not present.

This script tests to see if the user agent supports a (fictional) new format to dynamically decide whether to use a video element or a plugin:
<section id="video">
  <p><a href="playing-cats.nfv">Download video</a></p>
</section>
<script>
  var videoSection = document.getElementById('video');
  var videoElement = document.createElement('video');
  var support = videoElement.canPlayType('video/x-new-fictional-format;codecs="kittens,bunnies"');
  if (support != "probably" && "New Fictional Video Plugin" in navigator.plugins) {
    // not confident of browser support
    // but we have a plugin
    // so use plugin instead
    videoElement = document.createElement("embed");
  } else if (support == "") {
    // no support from browser and no plugin
    // do nothing
    videoElement = null;
  }
  if (videoElement) {
    while (videoSection.hasChildNodes())
      videoSection.removeChild(videoSection.firstChild);
    videoElement.setAttribute("src", "playing-cats.nfv");
    videoSection.appendChild(videoElement);
  }
</script>

The type attribute of the source element allows the user agent to avoid downloading resources that use formats it cannot render.

4.7.14.4. Network states
media . networkState

Returns the current state of network activity for the element, from the codes in the list below.

As media elements interact with the network, their current network activity is represented by the networkState attribute. On getting, it must return the current network state of the element, which must be one of the following values:

NETWORK_EMPTY (numeric value 0)
The element has not yet been initialized. All attributes are in their initial states.
NETWORK_IDLE (numeric value 1)
The element's resource selection algorithm is active and has selected a resource, but it is not actually using the network at this time.
NETWORK_LOADING (numeric value 2)
The user agent is actively trying to download data.
NETWORK_NO_SOURCE (numeric value 3)
The element's resource selection algorithm is active, but it has not yet found a resource to use.

The resource selection algorithm defined below describes exactly when the networkState attribute changes value and what events fire to indicate changes in this state.

4.7.14.5. Loading the media resource
media . load()

Causes the element to reset and start selecting and loading a new media resource from scratch.

All media elements have an autoplaying flag, which must begin in the true state, and a delaying-the-load-event flag, which must begin in the false state. While the delaying-the-load-event flag is true, the element must delay the load event of its document.

When the load() method on a media element is invoked, the user agent must run the media element load algorithm.

The media element load algorithm consists of the following steps.

  1. Abort any already-running instance of the resource selection algorithm for this element.
  2. If there are any tasks from the media element’s media element event task source in one of the task queues, then remove those tasks.

    Basically, pending events and callbacks for the media element are discarded when the media element starts loading a new resource.

  3. If the media element’s networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue a task to fire a simple event named abort at the media element.
  4. If the media element’s networkState is not set to NETWORK_EMPTY, then run these substeps:

    1. Queue a task to fire a simple event named emptied at the media element.
    2. If a fetching process is in progress for the media element, the user agent should stop it.
    3. If the media element’s assigned media provider object is a MediaSource object, then detach it.
    4. Forget the media element’s media-resource-specific tracks.
    5. If readyState is not set to HAVE_NOTHING, then set it to that state.
    6. If the paused attribute is false, then set it to true.
    7. If seeking is true, set it to false.
    8. Set the current playback position to 0.

      Set the official playback position to 0.

      If this changed the official playback position, then queue a task to fire a simple event named timeupdate at the media element.

    9. Set the initial playback position to 0.
    10. Set the timeline offset to Not-a-Number (NaN).
    11. Update the duration attribute to Not-a-Number (NaN).

      The user agent will not fire a durationchange event for this particular change of the duration.

  5. Set the playbackRate attribute to the value of the defaultPlaybackRate attribute.
  6. Set the error attribute to null and the autoplaying flag to true.
  7. Invoke the media element’s resource selection algorithm.
  8. Playback of any previously playing media resource for this element stops.

The resource selection algorithm for a media element is as follows. This algorithm is always invoked as part of a task, but one of the first steps in the algorithm is to return and continue running the remaining steps in parallel. In addition, this algorithm interacts closely with the event loop mechanism; in particular, it has synchronous sections (which are triggered as part of the event loop algorithm). Steps in such sections are marked with ⌛.

  1. Set the element’s networkState attribute to the NETWORK_NO_SOURCE value.
  2. Set the element’s show poster flag to true.
  3. Set the media element’s delaying-the-load-event flag to true (this delays the load event).
  4. in parallel await a stable state, allowing the task that invoked this algorithm to continue. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)
  5. ⌛ If the media element’s blocked-on-parser flag is false, then populate the list of pending text tracks.

  6. ⌛ If the media element has an assigned media provider object, then let mode be object.

    ⌛ Otherwise, if the media element has no assigned media provider object but has a src attribute, then let mode be attribute.

    ⌛ Otherwise, if the media element does not have an assigned media provider object and does not have a src attribute, but does have a source element child, then let mode be children and let candidate be the first such source element child in tree order.

    ⌛ Otherwise the media element has no assigned media provider object and has neither a src attribute nor a source element child: set the networkState to NETWORK_EMPTY, and abort these steps; the synchronous section ends.

  7. ⌛ Set the media element’s networkState to NETWORK_LOADING.
  8. Queue a task to fire a simple event named loadstart at the media element.
  9. Run the appropriate steps from the following list:

    If mode is object
    1. ⌛ Set the currentSrc attribute to the empty string.
    2. End the synchronous section, continuing the remaining steps in parallel.
    3. Run the resource fetch algorithm with the assigned media provider object. If that algorithm returns without aborting this one, then the load failed.
    4. Failed with media provider: Reaching this step indicates that the media resource failed to load. Queue a task to run the dedicated media source failure steps.
    5. Wait for the task queued by the previous step to have executed.
    6. Abort these steps. The element won’t attempt to load another resource until this algorithm is triggered again.
    If mode is attribute
    1. ⌛ If the src attribute’s value is the empty string, then end the synchronous section, and jump down to the failed with attribute step below.
    2. ⌛ Let absolute URL be the absolute URL that would have resulted from parsing the URL specified by the src attribute’s value relative to the media element when the src attribute was last changed.
    3. ⌛ If absolute URL was obtained successfully, set the currentSrc attribute to absolute URL.
    4. End the synchronous section, continuing the remaining steps in parallel.
    5. If absolute URL was obtained successfully, run the resource fetch algorithm with absolute URL. If that algorithm returns without aborting this one, then the load failed.
    6. Failed with attribute: Reaching this step indicates that the media resource failed to load or that the given URL could not be resolved. Queue a task to run the dedicated media source failure steps.
    7. Wait for the task queued by the previous step to have executed.
    8. Abort these steps. The element won’t attempt to load another resource until this algorithm is triggered again.
    Otherwise (mode is children)
    1. ⌛ Let pointer be a position defined by two adjacent nodes in the media element’s child list, treating the start of the list (before the first child in the list, if any) and end of the list (after the last child in the list, if any) as nodes in their own right. One node is the node before pointer, and the other node is the node after pointer. Initially, let pointer be the position between the candidate node and the next node, if there are any, or the end of the list, if it is the last node.

      As nodes are inserted and removed into the media element, pointer must be updated as follows:

      If a new node is inserted between the two nodes that define pointer
      Let pointer be the point between the node before pointer and the new node. In other words, insertions at pointer go after pointer.
      If the node before pointer is removed
      Let pointer be the point between the node after pointer and the node before the node after pointer. In other words, pointer doesn’t move relative to the remaining nodes.
      If the node after pointer is removed
      Let pointer be the point between the node before pointer and the node after the node before pointer. Just as with the previous case, pointer doesn’t move relative to the remaining nodes.

      Other changes don’t affect pointer.

    2. Process candidate: If candidate does not have a src attribute, or if its src attribute’s value is the empty string, then end the synchronous section, and jump down to the failed with elements step below.
    3. ⌛ Let absolute URL be the absolute URL that would have resulted from parsing the URL specified by candidate’s src attribute’s value relative to the candidate when the src attribute was last changed.
    4. ⌛ If absolute URL was not obtained successfully, then end the synchronous section, and jump down to the failed with elements step below.
    5. ⌛ If candidate has a type attribute whose value, when parsed as a MIME type (including any codecs described by the codecs parameter, for types that define that parameter), represents a type that the user agent knows it cannot render, then end the synchronous section, and jump down to the failed with elements step below.
    6. ⌛ Set the currentSrc attribute to absolute URL.
    7. End the synchronous section, continuing the remaining steps in parallel.
    8. Run the resource fetch algorithm with absolute URL. If that algorithm returns without aborting this one, then the load failed.
    9. Failed with elements: Queue a task to fire a simple event named error at the candidate element.
    10. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)
    11. Forget the media element’s media-resource-specific tracks.
    12. Find next candidate: Let candidate be null.
    13. Search loop: If the node after pointer is the end of the list, then jump to the waiting step below.
    14. ⌛ If the node after pointer is a source element, let candidate be that element.
    15. ⌛ Advance pointer so that the node before pointer is now the node that was after pointer, and the node after pointer is the node after the node that used to be after pointer, if any.
    16. ⌛ If candidate is null, jump back to the search loop step. Otherwise, jump back to the process candidate step.
    17. Waiting: Set the element’s networkState attribute to the NETWORK_NO_SOURCE value.
    18. ⌛ Set the element’s show poster flag to true.
    19. Queue a task to set the element’s delaying-the-load-event flag to false. This stops delaying the load event.
    20. End the synchronous section, continuing the remaining steps in parallel.
    21. Wait until the node after pointer is a node other than the end of the list. (This step might wait forever.)
    22. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)
    23. ⌛ Set the element’s delaying-the-load-event flag back to true (this delays the load event again, in case it hasn’t been fired yet).
    24. ⌛ Set the networkState back to NETWORK_LOADING.
    25. ⌛ Jump back to the find next candidate step above.

    The dedicated media source failure steps are the following steps:

    1. Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_SRC_NOT_SUPPORTED.
    2. Forget the media element’s media-resource-specific tracks.
    3. Set the element’s networkState attribute to the NETWORK_NO_SOURCE value.
    4. Set the element’s show poster flag to true.
    5. Fire a simple event named error at the media element.
    6. Set the element’s delaying-the-load-event flag to false. This stops delaying the load event.

The resource fetch algorithm for a media element and a given absolute URL or media provider object is as follows:

  1. If the algorithm was invoked with a URL, then let mode be remote, otherwise let mode be local.
  2. If mode is remote, then let the current media resource be the resource given by the absolute URL passed to this algorithm; otherwise, let the current media resource be the resource given by the media provider object. Either way, the current media resource is now the element’s media resource.
  3. Remove all media-resource-specific text tracks from the media element’s list of pending text tracks, if any.
  4. Run the appropriate steps from the following list:

    If mode is remote
    1. Optionally, run the following substeps. This is the expected behavior if the user agent intends to not attempt to fetch the resource until the user requests it explicitly (e.g., as a way to implement the preload attribute’s none keyword).

      1. Set the networkState to NETWORK_IDLE.
      2. Queue a task to fire a simple event named suspend at the element.
      3. Queue a task to set the element’s delaying-the-load-event flag to false. This stops delaying the load event.
      4. Wait for the task to be run.
      5. Wait for an implementation-defined event (e.g., the user requesting that the media element begin playback).
      6. Set the element’s delaying-the-load-event flag back to true (this delays the load event again, in case it hasn’t been fired yet).
      7. Set the networkState to NETWORK_LOADING.
    2. Let request be the result of creating a potential-CORS request given current media resource’s absolute URL and the media element’s crossorigin content attribute value.

      Set request’s client to the media element’s node document’s Window object’s environment settings object and type to "audio" if the media element is an audio element and to "video" otherwise.

      Fetch request.

      The response’s unsafe response obtained in this fashion, if any, contains the media data. It can be CORS-same-origin or CORS-cross-origin; this affects whether subtitles referenced in the media data are exposed in the API and, for video elements, whether a canvas gets tainted when the video is drawn on it.

      The stall timeout is a user-agent defined length of time, which should be about three seconds. When a media element that is actively attempting to obtain media data has failed to receive any data for a duration equal to the stall timeout, the user agent must queue a task to fire a simple event named stalled at the element.

      User agents may allow users to selectively block or slow media data downloads. When a media element’s download has been blocked altogether, the user agent must act as if it was stalled (as opposed to acting as if the connection was closed). The rate of the download may also be throttled automatically by the user agent, e.g., to balance the download with other connections sharing the same bandwidth.

      User agents may decide to not download more content at any time, e.g., after buffering five minutes of a one hour media resource, while waiting for the user to decide whether to play the resource or not, while waiting for user input in an interactive resource, or when the user navigates away from the page. When a media element’s download has been suspended, the user agent must queue a task, to set the networkState to NETWORK_IDLE and fire a simple event named suspend at the element. If and when downloading of the resource resumes, the user agent must queue a task to set the networkState to NETWORK_LOADING. Between the queuing of these tasks, the load is suspended (so progress events don’t fire, as described above).

      The preload attribute provides a hint regarding how much buffering the author thinks is advisable, even in the absence of the autoplay attribute.

      When a user agent decides to completely suspend a download, e.g., if it is waiting until the user starts playback before downloading any further content, the user agent must queue a task to set the element’s delaying-the-load-event flag to false. This stops delaying the load event.

      The user agent may use whatever means necessary to fetch the resource (within the constraints put forward by this and other specifications); for example, reconnecting to the server in the face of network errors, using HTTP range retrieval requests, or switching to a streaming protocol. The user agent must consider a resource erroneous only if it has given up trying to fetch it.

      To determine the format of the media resource, the user agent must use the rules for sniffing audio and video specifically.

      While the load is not suspended (see below), every 350ms (±200ms) or for every byte received, whichever is least frequent, queue a task to fire a simple event named progress at the element.

      The networking task source tasks to process the data as it is being fetched must each immediately queue a task to run the first appropriate steps from the media data processing steps list below. (A new task is used for this so that the work described below occurs relative to the media element event task source rather than the networking task source.)

      When the networking task source has queued the last task as part of fetching the media resource (i.e., once the download has completed), if the fetching process completes without errors, including decoding the media data, and if all of the data is available to the user agent without network access, then, the user agent must move on to the final step below. This might never happen, e.g., when streaming an infinite resource such as Web radio, or if the resource is longer than the user agent’s ability to cache data.

      While the user agent might still need network access to obtain parts of the media resource, the user agent must remain on this step.

      For example, if the user agent has discarded the first half of a video, the user agent will remain at this step even once the playback has ended, because there is always the chance the user will seek back to the start. In fact, in this situation, once playback has ended, the user agent will end up firing a suspend event, as described earlier.

    Otherwise (mode is local)

    The resource described by the current media resource, if any, contains the media data. It is CORS-same-origin.

    If the current media resource is a raw data stream (e.g., from a File object), then to determine the format of the media resource, the user agent must use the rules for sniffing audio and video specifically. Otherwise, if the data stream is pre-decoded, then the format is the format given by the relevant specification.

    Whenever new data for the current media resource becomes available, queue a task to run the first appropriate steps from the media data processing steps list below.

    When the current media resource is permanently exhausted (e.g., all the bytes of a Blob have been processed), if there were no decoding errors, then the user agent must move on to the final step below. This might never happen, e.g., if the current media resource is a MediaStream.

    The media data processing steps list is as follows:

    If the media data cannot be fetched at all, due to network errors, causing the user agent to give up trying to fetch the resource
    If the media data can be fetched but is found by inspection to be in an unsupported format, or can otherwise not be rendered at all

    DNS errors, HTTP 4xx and 5xx errors (and equivalents in other protocols), and other fatal network errors that occur before the user agent has established whether the current media resource is usable, as well as the file using an unsupported container format, or using unsupported codecs for all the data, must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.
    2. Abort this subalgorithm, returning to the resource selection algorithm.
    If the media resource is found to have an audio track
    1. Create an AudioTrack object to represent the audio track.
    2. Update the media element’s audioTracks attribute’s AudioTrackList object with the new AudioTrack object.
    3. Let enable be unknown.
    4. If either the media resource or the address of the current media resource indicate a particular set of audio tracks to enable, or if the user agent has information that would facilitate the selection of specific audio tracks to improve the user’s experience, then: if this audio track is one of the ones to enable, then set enable to true, otherwise, set enable to false.

      This could be triggered by Media Fragments URI fragment identifier syntax, but it could also be triggered e.g., by the user agent selecting a 5.1 surround sound audio track over a stereo audio track. [MEDIA-FRAGS]

    5. If enable is still unknown, then, if the media element does not yet have an enabled audio track, then set enable to true, otherwise, set enable to false.
    6. If enable is true, then enable this audio track, otherwise, do not enable this audio track.
    7. Fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the new AudioTrack object, at this AudioTrackList object.
    If the media resource is found to have a video track
    1. Create a VideoTrack object to represent the video track.
    2. Update the media element’s videoTracks attribute’s VideoTrackList object with the new VideoTrack object.
    3. Let enable be unknown.
    4. If either the media resource or the address of the current media resource indicate a particular set of video tracks to enable, or if the user agent has information that would facilitate the selection of specific video tracks to improve the user’s experience, then: if this video track is the first such video track, then set enable to true, otherwise, set enable to false.

      This could again be triggered by Media Fragments URI fragment identifier syntax.

    5. If enable is still unknown, then, if the media element does not yet have a selected video track, then set enable to true, otherwise, set enable to false.
    6. If enable is true, then select this track and unselect any previously selected video tracks, otherwise, do not select this video track. If other tracks are unselected, then a change event will be fired.
    7. Fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the new VideoTrack object, at this VideoTrackList object.
    Once enough of the media data has been fetched to determine the duration of the media resource, its dimensions, and other metadata

    This indicates that the resource is usable. The user agent must follow these substeps:

    1. Establish the media timeline for the purposes of the current playback position and the earliest possible position, based on the media data.

    2. Update the timeline offset to the date and time that corresponds to the zero time in the media timeline established in the previous step, if any. If no explicit time and date is given by the media resource, the timeline offset must be set to Not-a-Number (NaN).

    3. Set the current playback position and the official playback position to the earliest possible position.
    4. Update the duration attribute with the time of the last frame of the resource, if known, on the media timeline established above. If it is not known (e.g., a stream that is in principle infinite), update the duration attribute to the value positive Infinity.

      The user agent will queue a task to fire a simple event named durationchange at the element at this point.

    5. For video elements, set the videoWidth and videoHeight attributes, and queue a task to fire a simple event named resize at the media element.

      Further resize events will be fired if the dimensions subsequently change.

    6. Set the readyState attribute to HAVE_METADATA.

      A loadedmetadata DOM event will be fired as part of setting the readyState attribute to a new value.

    7. Let jumped be false.
    8. If the media element’s default playback start position is greater than zero, then seek to that time, and let jumped be true.
    9. Let the media element’s default playback start position be zero.
    10. Let the initial playback position be zero.
    11. If either the media resource or the address of the current media resource indicate a particular start time, then set the initial playback position to that time and, if jumped is still false, seek to that time and let jumped be true.

      For example, with media formats that support the Media Fragments URI fragment identifier syntax, the fragment identifier can be used to indicate a start position. [MEDIA-FRAGS]

    12. If there is no enabled audio track, then enable an audio track. This will cause a change event to be fired.
    13. If there is no selected video track, then select a video track. This will cause a change event to be fired.

    Once the readyState attribute reaches HAVE_CURRENT_DATA, after the loadeddata event has been fired, set the element’s delaying-the-load-event flag to false. This stops delaying the load event.

    A user agent that is attempting to reduce network usage while still fetching the metadata for each media resource would also stop buffering at this point, following the rules described previously, which involve the networkState attribute switching to the NETWORK_IDLE value and a suspend event firing.

    The user agent is required to determine the duration of the media resource and go through this step before playing.

    Once the entire media resource has been fetched (but potentially before any of it has been decoded)

    Fire a simple event named progress at the media element.

    Set the networkState to NETWORK_IDLE and fire a simple event named suspend at the media element.

    If the user agent ever discards any media data and then needs to resume the network activity to obtain it again, then it must queue a task to set the networkState to NETWORK_LOADING.

    If the user agent can keep the media resource loaded, then the algorithm will continue to its final step below, which aborts the algorithm.

    If the connection is interrupted after some media data has been received, causing the user agent to give up trying to fetch the resource

    Fatal network errors that occur after the user agent has established whether the current media resource is usable (i.e., once the media element’s readyState attribute is no longer HAVE_NOTHING) must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.
    2. Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_NETWORK.
    3. Set the element’s networkState attribute to the NETWORK_IDLE value.
    4. Set the element’s delaying-the-load-event flag to false. This stops delaying the load event.
    5. Fire a simple event named error at the media element.
    6. Abort the overall resource selection algorithm.
    If the media data is corrupted

    Fatal errors in decoding the media data that occur after the user agent has established whether the current media resource is usable (i.e., once the media element’s readyState attribute is no longer HAVE_NOTHING) must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.
    2. Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_DECODE.
    3. Set the element’s networkState attribute to the NETWORK_IDLE value.
    4. Set the element’s delaying-the-load-event flag to false. This stops delaying the load event.
    5. Fire a simple event named error at the media element.
    6. Abort the overall resource selection algorithm.
    If the media data fetching process is aborted by the user

    The fetching process is aborted by the user, e.g., because the user pressed a "stop" button, the user agent must execute the following steps. These steps are not followed if the load() method itself is invoked while these steps are running, as the steps above handle that particular kind of abort.

    1. The user agent should cancel the fetching process.
    2. Set the error attribute to a new MediaError object whose code attribute is set to MEDIA_ERR_ABORTED.
    3. Fire a simple event named abort at the media element.
    4. If the media element’s readyState attribute has a value equal to HAVE_NOTHING, set the element’s networkState attribute to the NETWORK_EMPTY value, set the element’s show poster flag to true, and fire a simple event named emptied at the element.

      Otherwise, set the element’s networkState attribute to the NETWORK_IDLE value.

    5. Set the element’s delaying-the-load-event flag to false. This stops delaying the load event.
    6. Abort the overall resource selection algorithm.
    If the media data can be fetched but has non-fatal errors or uses, in part, codecs that are unsupported, preventing the user agent from rendering the content completely correctly but not preventing playback altogether

    The server returning data that is partially usable but cannot be optimally rendered must cause the user agent to render just the bits it can handle, and ignore the rest.

    If the media resource is found to declare a media-resource-specific text track that the user agent supports

    If the media data is CORS-same-origin, run the steps to expose a media-resource-specific text track with the relevant data.

    Cross-origin videos do not expose their subtitles, since that would allow attacks such as hostile sites reading subtitles from confidential videos on a user’s intranet.

  5. Final step: If the user agent ever reaches this step (which can only happen if the entire resource gets loaded and kept available): abort the overall resource selection algorithm.

When a media element is to forget the media element’s media-resource-specific tracks, the user agent must remove from the media element’s list of text tracks all the media-resource-specific text tracks, then empty the media element’s audioTracks attribute’s AudioTrackList object, then empty the media element’s videoTracks attribute’s VideoTrackList object. No events (in particular, no removetrack events) are fired as part of this; the error and emptied events, fired by the algorithms that invoke this one, can be used instead.


The preload attribute is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword. The attribute can be changed even once the media resource is being buffered or played; the descriptions in the table below are to be interpreted with that in mind.

Keyword State Brief description
none None Hints to the user agent that either the author does not expect the user to need the media resource, or that the server wants to minimize unnecessary traffic. This state does not provide a hint regarding how aggressively to actually download the media resource if buffering starts anyway (e.g., once the user hits "play").
metadata Metadata Hints to the user agent that the author does not expect the user to need the media resource, but that fetching the resource metadata (dimensions, track list, duration, etc), and maybe even the first few frames, is reasonable. If the user agent precisely fetches no more than the metadata, then the media element will end up with its readyState attribute set to HAVE_METADATA; typically though, some frames will be obtained as well and it will probably be HAVE_CURRENT_DATA or HAVE_FUTURE_DATA. When the media resource is playing, hints to the user agent that bandwidth is to be considered scarce, e.g., suggesting throttling the download so that the media data is obtained at the slowest possible rate that still maintains consistent playback.
auto Automatic Hints to the user agent that the user agent can put the user’s needs first without risk to the server, up to and including optimistically downloading the entire resource.

The empty string is also a valid keyword, and maps to the Automatic state. The attribute’s missing value default is user-agent defined, though the Metadata state is suggested as a compromise between reducing server load and providing an optimal user experience.

Authors might switch the attribute from "none" or "metadata" to "auto" dynamically once the user begins playback. For example, on a page with many videos this might be used to indicate that the many videos are not to be downloaded unless requested, but that once one is requested it is to be downloaded aggressively.

The preload attribute is intended to provide a hint to the user agent about what the author thinks will lead to the best user experience. The attribute may be ignored altogether, for example based on explicit user preferences or based on the available connectivity.

The preload IDL attribute must reflect the content attribute of the same name, limited to only known values.

The autoplay attribute can override the preload attribute (since if the media plays, it naturally has to buffer first, regardless of the hint given by the preload attribute). Including both is not an error, however.


media . buffered

Returns a TimeRanges object that represents the ranges of the media resource that the user agent has buffered.

The buffered attribute must return a new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent has buffered, at the time the attribute is evaluated. Users agents must accurately determine the ranges available, even for media streams where this can only be determined by tedious inspection.

Typically this will be a single range anchored at the zero point, but if, e.g., the user agent uses HTTP range requests in response to seeking, then there could be multiple ranges.

User agents may discard previously buffered data.

Thus, a time position included within a range of the objects return by the buffered attribute at one time can end up being not included in the range(s) of objects returned by the same attribute at later times.

4.7.14.6. Offsets into the media resource
media . duration

Returns the length of the media resource, in seconds, assuming that the start of the media resource is at time zero.

Returns NaN if the duration isn’t available.

Returns Infinity for unbounded streams.

media . currentTime [ = value ]

Returns the official playback position, in seconds.

Can be set, to seek to the given time.

A media resource has a media timeline that maps times (in seconds) to positions in the media resource. The origin of a timeline is its earliest defined position. The duration of a timeline is its last defined position.

Establishing the media timeline: If the media resource somehow specifies an explicit timeline whose origin is not negative (i.e., gives each frame a specific time offset and gives the first frame a zero or positive offset), then the media timeline should be that timeline. (Whether the media resource can specify a timeline or not depends on the media resource’s format.) If the media resource specifies an explicit start time and date, then that time and date should be considered the zero point in the media timeline; the timeline offset will be the time and date, exposed using the getStartDate() method.

If the media resource has a discontinuous timeline, the user agent must extend the timeline used at the start of the resource across the entire resource, so that the media timeline of the media resource increases linearly starting from the earliest possible position (as defined below), even if the underlying media data has out-of-order or even overlapping time codes.

For example, if two clips have been concatenated into one video file, but the video format exposes the original times for the two clips, the video data might expose a timeline that goes, say, 00:15..00:29 and then 00:05..00:38. However, the user agent would not expose those times; it would instead expose the times as 00:15..00:29 and 00:29..01:02, as a single video.

In the rare case of a media resource that does not have an explicit timeline, the zero time on the media timeline should correspond to the first frame of the media resource. In the even rarer case of a media resource with no explicit timings of any kind, not even frame durations, the user agent must itself determine the time for each frame in a user-agent-defined manner. (This is a fingerprinting vector.)

An example of a file format with no explicit timeline but with explicit frame durations is the Animated GIF format. An example of a file format with no explicit timings at all is the JPEG-push format (multipart/x-mixed-replace with JPEG frames, often used as the format for MJPEG streams).

If, in the case of a resource with no timing information, the user agent will nonetheless be able to seek to an earlier point than the first frame originally provided by the server, then the zero time should correspond to the earliest seekable time of the media resource; otherwise, it should correspond to the first frame received from the server (the point in the media resource at which the user agent began receiving the stream).

At the time of writing, there is no known format that lacks explicit frame time offsets yet still supports seeking to a frame before the first frame sent by the server.

Consider a stream from a TV broadcaster, which begins streaming on a sunny Friday afternoon in October, and always sends connecting user agents the media data on the same media timeline, with its zero time set to the start of this stream. Months later, user agents connecting to this stream will find that the first frame they receive has a time with millions of seconds. The getStartDate() method would always return the date that the broadcast started; this would allow controllers to display real times in their scrubber (e.g., "2:30pm") rather than a time relative to when the broadcast began ("8 months, 4 hours, 12 minutes, and 23 seconds").

Consider a stream that carries a video with several concatenated fragments, broadcast by a server that does not allow user agents to request specific times but instead just streams the video data in a predetermined order, with the first frame delivered always being identified as the frame with time zero. If a user agent connects to this stream and receives fragments defined as covering timestamps 2010-03-20 23:15:00 UTC to 2010-03-21 00:05:00 UTC and 2010-02-12 14:25:00 UTC to 2010-02-12 14:35:00 UTC, it would expose this with a media timeline starting at 0s and extending to 3,600s (one hour). Assuming the streaming server disconnected at the end of the second clip, the duration attribute would then return 3,600. The getStartDate() method would return a Date object with a time corresponding to 2010-03-20 23:15:00 UTC. However, if a different user agent connected five minutes later, it would (presumably) receive fragments covering timestamps 2010-03-20 23:20:00 UTC to 2010-03-21 00:05:00 UTC and 2010-02-12 14:25:00 UTC to 2010-02-12 14:35:00 UTC, and would expose this with a media timeline starting at 0s and extending to 3,300s (fifty five minutes). In this case, the getStartDate() method would return a Date object with a time corresponding to 2010-03-20 23:20:00 UTC.

In both of these examples, the seekable attribute would give the ranges that the controller would want to actually display in its UI; typically, if the servers don’t support seeking to arbitrary times, this would be the range of time from the moment the user agent connected to the stream up to the latest frame that the user agent has obtained; however, if the user agent starts discarding earlier information, the actual range might be shorter.

In any case, the user agent must ensure that the earliest possible position (as defined below) using the established media timeline, is greater than or equal to zero.

The media timeline also has an associated clock. Which clock is used is user-agent defined, and may be media resource-dependent, but it should approximate the user’s wall clock.

Media elements have a current playback position, which must initially (i.e., in the absence of media data) be zero seconds. The current playback position is a time on the media timeline.

Media elements also have an official playback position, which must initially be set to zero seconds. The official playback position is an approximation of the current playback position that is kept stable while scripts are running.

Media elements also have a default playback start position, which must initially be set to zero seconds. This time is used to allow the element to be seeked even before the media is loaded.

Each media element has a show poster flag. When a media element is created, this flag must be set to true. This flag is used to control when the user agent is to show a poster frame for a video element instead of showing the video contents.

The currentTime attribute must, on getting, return the media element’s default playback start position, unless that is zero, in which case it must return the element’s official playback position. The returned value must be expressed in seconds. On setting, if the media element’s readyState is HAVE_NOTHING, then it must set the media element’s default playback start position to the new value; otherwise, it must set the official playback position to the new value and then seek to the new value. The new value must be interpreted as being in seconds.

Media elements have an initial playback position, which must initially (i.e., in the absence of media data) be zero seconds. The initial playback position is updated when a media resource is loaded. The initial playback position is a time on the media timeline.

If the media resource is a streaming resource, then the user agent might be unable to obtain certain parts of the resource after it has expired from its buffer. Similarly, some media resources might have a media timeline that doesn’t start at zero. The earliest possible position is the earliest position in the stream or resource that the user agent can ever obtain again. It is also a time on the media timeline.

The earliest possible position is not explicitly exposed in the API; it corresponds to the start time of the first range in the seekable attribute’s TimeRanges object, if any, or the current playback position otherwise.

When the earliest possible position changes, then: if the current playback position is before the earliest possible position, the user agent must seek to the earliest possible position; otherwise, if the user agent has not fired a timeupdate event at the element in the past 15 to 250ms and is not still running event handlers for such an event, then the user agent must queue a task to fire a simple event named timeupdate at the element.

Because of the above requirement and the requirement in the resource fetch algorithm that kicks in when the metadata of the clip becomes known, the current playback position can never be less than the earliest possible position.

If at any time the user agent learns that an audio or video track has ended and all media data relating to that track corresponds to parts of the media timeline that are before the earliest possible position, the user agent may queue a task to first remove the track from the audioTracks attribute’s AudioTrackList object or the videoTracks attribute’s VideoTrackList object as appropriate and then fire a trusted event with the name removetrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the AudioTrack or VideoTrack object representing the track, at the media element’s aforementioned AudioTrackList or VideoTrackList object.

The duration attribute must return the time of the end of the media resource, in seconds, on the media timeline. If no media data is available, then the attributes must return the Not-a-Number (NaN) value. If the media resource is not known to be bounded (e.g., streaming radio, or a live event with no announced end time), then the attribute must return the positive Infinity value.

The user agent must determine the duration of the media resource before playing any part of the media data and before setting readyState to a value equal to or greater than HAVE_METADATA, even if doing so requires fetching multiple parts of the resource.

When the length of the media resource changes to a known value (e.g., from being unknown to known, or from a previously established length to a new length) the user agent must queue a task to fire a simple event named durationchange at the media element. (The event is not fired when the duration is reset as part of loading a new media resource.) If the duration is changed such that the current playback position ends up being greater than the time of the end of the media resource, then the user agent must also seek to the time of the end of the media resource.

If an "infinite" stream ends for some reason, then the duration would change from positive Infinity to the time of the last frame or sample in the stream, and the durationchange event would be fired. Similarly, if the user agent initially estimated the media resource’s duration instead of determining it precisely, and later revises the estimate based on new information, then the duration would change and the durationchange event would be fired.

Some video files also have an explicit date and time corresponding to the zero time in the media timeline, known as the timeline offset. Initially, the timeline offset must be set to Not-a-Number (NaN).

The getStartDate() method must return a new Date object representing the current timeline offset.


The loop attribute is a boolean attribute that, if specified, indicates that the media element is to seek back to the start of the media resource upon reaching the end.

The loop IDL attribute must reflect the content attribute of the same name.

4.7.14.7. Ready states
media . readyState

Returns a value that expresses the current state of the element with respect to rendering the current playback position, from the codes in the list below.

Media elements have a ready state, which describes to what degree they are ready to be rendered at the current playback position. The possible values are as follows; the ready state of a media element at any particular time is the greatest value describing the state of the element:

HAVE_NOTHING (numeric value 0)
No information regarding the media resource is available. No data for the current playback position is available. Media elements whose networkState attribute are set to NETWORK_EMPTY are always in the HAVE_NOTHING state.
HAVE_METADATA (numeric value 1)
Enough of the resource has been obtained that the duration of the resource is available. In the case of a video element, the dimensions of the video are also available. No media data is available for the immediate current playback position.
HAVE_CURRENT_DATA (numeric value 2)
Data for the immediate current playback position is available, but either not enough data is available that the user agent could successfully advance the current playback position in the direction of playback at all without immediately reverting to the HAVE_METADATA state, or there is no more data to obtain in the direction of playback. For example, in video this corresponds to the user agent having data from the current frame, but not the next frame, when the current playback position is at the end of the current frame; and to when playback has ended.
HAVE_FUTURE_DATA (numeric value 3)
Data for the immediate current playback position is available, as well as enough data for the user agent to advance the current playback position in the direction of playback at least a little without immediately reverting to the HAVE_METADATA state, and the text tracks are ready. For example, in video this corresponds to the user agent having data for at least the current frame and the next frame when the current playback position is at the instant in time between the two frames, or to the user agent having the video data for the current frame and audio data to keep playing at least a little when the current playback position is in the middle of a frame. The user agent cannot be in this state if playback has ended, as the current playback position can never advance in this case.
HAVE_ENOUGH_DATA (numeric value 4)

All the conditions described for the HAVE_FUTURE_DATA state are met, and, in addition, either of the following conditions is also true:

  • The user agent estimates that data is being fetched at a rate where the current playback position, if it were to advance at the effective playback rate, would not overtake the available data before playback reaches the end of the media resource.
  • The user agent has entered a state where waiting longer will not result in further data being obtained, and therefore nothing would be gained by delaying playback any further. (For example, the buffer might be full.)

In practice, the difference between HAVE_METADATA and HAVE_CURRENT_DATA is negligible. Really the only time the difference is relevant is when painting a video element onto a canvas, where it distinguishes the case where something will be drawn (HAVE_CURRENT_DATA or greater) from the case where nothing is drawn (HAVE_METADATA or less). Similarly, the difference between HAVE_CURRENT_DATA (only the current frame) and HAVE_FUTURE_DATA (at least this frame and the next) can be negligible (in the extreme, only one frame). The only time that distinction really matters is when a page provides an interface for "frame-by-frame" navigation.

When the ready state of a media element whose networkState is not NETWORK_EMPTY changes, the user agent must follow the steps given below:

  1. Apply the first applicable set of substeps from the following list:

    If the previous ready state was HAVE_NOTHING, and the new ready state is HAVE_METADATA

    Queue a task to fire a simple event named loadedmetadata at the element.

    Before this task is run, as part of the event loop mechanism, the rendering will have been updated to resize the video element if appropriate.

    If the previous ready state was HAVE_METADATA and the new ready state is HAVE_CURRENT_DATA or greater

    If this is the first time this occurs for this media element since the load() algorithm was last invoked, the user agent must queue a task to fire a simple event named loadeddata at the element.

    If the new ready state is HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA, then the relevant steps below must then be run also.

    If the previous ready state was HAVE_FUTURE_DATA or more, and the new ready state is HAVE_CURRENT_DATA or less

    If the media element was potentially playing before its readyState attribute changed to a value lower than HAVE_FUTURE_DATA, and the element has not ended playback, and playback has not stopped due to errors, paused for user interaction, or paused for in-band content, the user agent must queue a task to fire a simple event named timeupdate at the element, and queue a task to fire a simple event named waiting at the element.

    If the previous ready state was HAVE_CURRENT_DATA or less, and the new ready state is HAVE_FUTURE_DATA

    The user agent must queue a task to fire a simple event named canplay at the element.

    If the element’s paused attribute is false, the user agent must queue a task to fire a simple event named playing at the element.

    If the new ready state is HAVE_ENOUGH_DATA

    If the previous ready state was HAVE_CURRENT_DATA or less, the user agent must queue a task to fire a simple event named canplay at the element, and, if the element’s paused attribute is false, queue a task to fire a simple event named playing at the element.

    If the autoplaying flag is true, and the paused attribute is true, and the media element has an autoplay attribute specified, and the media element’s node document’s active sandboxing flag set does not have the sandboxed automatic features browsing context flag set, then the user agent may also run the following substeps:

    1. Set the paused attribute to false.
    2. If the element’s show poster flag is true, set it to false and run the time marches on steps.
    3. Queue a task to fire a simple event named play at the element.
    4. Queue a task to fire a simple event named playing at the element.
    5. Set the autoplaying flag to false.

    User agents do not need to support autoplay, and it is suggested that user agents honor user preferences on the matter. Authors are urged to use the autoplay attribute rather than using script to force the video to play, so as to allow the user to override the behavior if so desired.

    In any case, the user agent must finally queue a task to fire a simple event named canplaythrough at the element.

It is possible for the ready state of a media element to jump between these states discontinuously. For example, the state of a media element can jump straight from HAVE_METADATA to HAVE_ENOUGH_DATA without passing through the HAVE_CURRENT_DATA and HAVE_FUTURE_DATA states.

The readyState IDL attribute must, on getting, return the value described above that describes the current ready state of the media element.

The autoplay attribute is a boolean attribute. When present, the user agent (as described in the algorithm described herein) will automatically begin playback of the media resource as soon as it can do so without stopping.

Authors are urged to use the autoplay attribute rather than using script to trigger automatic playback, as this allows the user to override the automatic playback when it is not desired, e.g., when using a screen reader. Authors are also encouraged to consider not using the automatic playback behavior at all, and instead to let the user agent wait for the user to start playback explicitly.

The autoplay IDL attribute must reflect the content attribute of the same name.

4.7.14.8. Playing the media resource
media . paused

Returns true if playback is paused; false otherwise.

media . ended

Returns true if playback has reached the end of the media resource.

media . defaultPlaybackRate [ = value ]

Returns the default rate of playback, for when the user is not fast-forwarding or reversing through the media resource.

Can be set, to change the default rate of playback.

The default rate has no direct effect on playback, but if the user switches to a fast-forward mode, when they return to the normal playback mode, it is expected that the rate of playback will be returned to the default rate of playback.

media . playbackRate [ = value ]

Returns the current rate playback, where 1.0 is normal speed.

Can be set, to change the rate of playback.

media . played

Returns a TimeRanges object that represents the ranges of the media resource that the user agent has played.

media . play()

Sets the paused attribute to false, loading the media resource and beginning playback if necessary. If the playback had ended, will restart it from the start.

media . pause()

Sets the paused attribute to true, loading the media resource if necessary.

The paused attribute represents whether the media element is paused or not. The attribute must initially be true.

A media element is a blocked media element if its readyState attribute is in the HAVE_NOTHING state, the HAVE_METADATA state, or the HAVE_CURRENT_DATA state, or if the element has paused for user interaction or paused for in-band content.

A media element is said to be potentially playing when its paused attribute is false, the element has not ended playback, playback has not stopped due to errors, and the element is not a blocked media element.

A waiting DOM event can be fired as a result of an element that is potentially playing stopping playback due to its readyState attribute changing to a value lower than HAVE_FUTURE_DATA.

A media element is said to have ended playback when:

The ended attribute must return true if, the last time the event loop reached step 1, the media element had ended playback and the direction of playback was forwards, and false otherwise.

A media element is said to have stopped due to errors when the element’s readyState attribute is HAVE_METADATA or greater, and the user agent encounters a non-fatal error during the processing of the media data, and due to that error, is not able to play the content at the current playback position.

A media element is said to have paused for user interaction when its paused attribute is false, the readyState attribute is either HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA and the user agent has reached a point in the media resource where the user has to make a selection for the resource to continue.

It is possible for a media element to have both ended playback and paused for user interaction at the same time.

When a media element that is potentially playing stops playing because it has paused for user interaction, the user agent must queue a task to fire a simple event named timeupdate at the element.

A media element is said to have paused for in-band content when its paused attribute is false, the readyState attribute is either HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA and the user agent has suspended playback of the media resource in order to play content that is temporally anchored to the media resource and has a non-zero length, or to play content that is temporally anchored to a segment of the media resource but has a length longer than that segment.

One example of when a media element would be paused for in-band content is when the user agent is playing audio descriptions from an external WebVTT file, and the synthesized speech generated for a cue is longer than the time between the text track cue start time and the text track cue end time.


When the current playback position reaches the end of the media resource when the direction of playback is forwards, then the user agent must follow these steps:

  1. If the media element has a loop attribute specified, then seek to the earliest possible position of the media resource and abort these steps.
  2. As defined above, the ended IDL attribute starts returning true once the event loop returns to step 1.
  3. Queue a task to fire a simple event named timeupdate at the media element.
  4. Queue a task that, if the media element has still ended playback, and the direction of playback is still forwards, and paused is false, changes paused to true and fires a simple event named pause at the media element.
  5. Queue a task to fire a simple event named ended at the media element.

When the current playback position reaches the earliest possible position of the media resource when the direction of playback is backwards, then the user agent must only queue a task to fire a simple event named timeupdate at the element.

The word "reaches" here does not imply that the current playback position needs to have changed during normal playback; it could be via seeking, for instance.


The defaultPlaybackRate attribute gives the desired speed at which the media resource is to play, as a multiple of its intrinsic speed. The attribute is mutable: on getting it must return the last value it was set to, or 1.0 if it hasn’t yet been set; on setting the attribute must be set to the new value.

The defaultPlaybackRate is used by the user agent when it exposes a user interface to the user.

The playbackRate attribute gives the effective playback rate which is the speed at which the media resource plays, as a multiple of its intrinsic speed. If it is not equal to the defaultPlaybackRate, then the implication is that the user is using a feature such as fast forward or slow motion playback. The attribute is mutable: on getting it must return the last value it was set to, or 1.0 if it hasn’t yet been set; on setting the attribute must be set to the new value, and the playback will change speed (if the element is potentially playing).

When the defaultPlaybackRate or playbackRate attributes change value (either by being set by script or by being changed directly by the user agent, e.g., in response to user control) the user agent must queue a task to fire a simple event named ratechange at the media element.


The played attribute must return a new static normalized TimeRanges object that represents the ranges of points on the media timeline of the media resource reached through the usual monotonic increase of the current playback position during normal playback, if any, at the time the attribute is evaluated.


When the play() method on a media element is invoked, the user agent must run the following steps.

  1. If the media element’s networkState attribute has the value NETWORK_EMPTY, invoke the media element’s resource selection algorithm.
  2. If the playback has ended and the direction of playback is forwards, seek to the earliest possible position of the media resource.

    This will cause the user agent to queue a task to fire a simple event named timeupdate at the media element.

  3. If the media element’s paused attribute is true, run the following substeps:

    1. Change the value of paused to false.
    2. If the show poster flag is true, set the element’s show poster flag to false and run the time marches on steps.
    3. Queue a task to fire a simple event named play at the element.
    4. If the media element’s readyState attribute has the value HAVE_NOTHING, HAVE_METADATA, or HAVE_CURRENT_DATA, queue a task to fire a simple event named waiting at the element.

      Otherwise, the media element’s readyState attribute has the value HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA: queue a task to fire a simple event named playing at the element.

  4. Set the media element’s autoplaying flag to false.

When the pause() method is invoked, and when the user agent is required to pause the media element, the user agent must run the following steps:

  1. If the media element’s networkState attribute has the value NETWORK_EMPTY, invoke the media element’s resource selection algorithm.
  2. Run the internal pause steps for the media element.

The internal pause steps for a media element are as follows:

  1. Set the media element’s autoplaying flag to false.
  2. If the media element’s paused attribute is false, run the following steps:
    1. Change the value of paused to true.
    2. Queue a task to fire a simple event named timeupdate at the element.
    3. Queue a task to fire a simple event named pause at the element.
    4. Set the official playback position to the current playback position.

The effective playback rate is just the element’s playbackRate.

If the effective playback rate is positive or zero, then the direction of playback is forwards. Otherwise, it is backwards.

When a media element is potentially playing and its Document is a fully active Document, its current playback position must increase monotonically at effective playback rate units of media time per unit time of the media timeline’s clock. (This specification always refers to this as an increase, but that increase could actually be a decrease if the effective playback rate is negative.)

The effective playback rate can be 0.0, in which case the current playback position doesn’t move, despite playback not being paused (paused doesn’t become true, and the pause event doesn’t fire).

This specification doesn’t define how the user agent achieves the appropriate playback rate — depending on the protocol and media available, it is plausible that the user agent could negotiate with the server to have the server provide the media data at the appropriate rate, so that (except for the period between when the rate is changed and when the server updates the stream’s playback rate) the client doesn’t actually have to drop or interpolate any frames.

Any time the user agent provides a stable state, the official playback position must be set to the current playback position.

While the direction of playback is backwards, any corresponding audio must be muted. While the effective playback rate is so low or so high that the user agent cannot play audio usefully, the corresponding audio must also be muted. If the effective playback rate is not 1.0, the user agent may apply pitch adjustments to the audio as necessary to render it faithfully.

Media elements that are potentially playing while not in a Document must not play any video, but should play any audio component. Media elements must not stop playing just because all references to them have been removed; only once a media element is in a state where no further audio could ever be played by that element may the element be garbage collected.

It is possible for an element to which no explicit references exist to play audio, even if such an element is not still actively playing: for instance, a media element whose media resource has no audio tracks could eventually play audio again if it had an event listener that changes the media resource.


Each media element has a list of newly introduced cues, which must be initially empty. Whenever a text track cue is added to the list of cues of a text track that is in the list of text tracks for a media element, that cue must be added to the media element’s list of newly introduced cues. Whenever a text track is added to the list of text tracks for a media element, all of the cues in that text track’s list of cues must be added to the media element’s list of newly introduced cues. When a media element’s list of newly introduced cues has new cues added while the media element’s show poster flag is not set, then the user agent must run the time marches on steps.

When a text track cue is removed from the list of cues of a text track that is in the list of text tracks for a media element, and whenever a text track is removed from the list of text tracks of a media element, if the media element’s show poster flag is not set, then the user agent must run the time marches on steps.

When the current playback position of a media element changes (e.g., due to playback or seeking), the user agent must run the time marches on steps. If the current playback position changes while the steps are running, then the user agent must wait for the steps to complete, and then must immediately rerun the steps. (These steps are thus run as often as possible or needed — if one iteration takes a long time, this can cause certain cues to be skipped over as the user agent rushes ahead to "catch up".)

The time marches on steps are as follows:

  1. Let current cues be a list of cues, initialized to contain all the cues of all the hidden or showing text tracks of the media element (not the disabled ones) whose start times are less than or equal to the current playback position and whose end times are greater than the current playback position.
  2. Let other cues be a list of cues, initialized to contain all the cues of hidden and showing text tracks of the media element that are not present in current cues.
  3. Let last time be the current playback position at the time this algorithm was last run for this media element, if this is not the first time it has run.
  4. If the current playback position has, since the last time this algorithm was run, only changed through its usual monotonic increase during normal playback, then let missed cues be the list of cues in other cues whose start times are greater than or equal to last time and whose end times are less than or equal to the current playback position. Otherwise, let missed cues be an empty list.
  5. Remove all the cues in missed cues that are also in the media element’s list of newly introduced cues, and then empty the element’s list of newly introduced cues.
  6. If the time was reached through the usual monotonic increase of the current playback position during normal playback, and if the user agent has not fired a timeupdate event at the element in the past 15 to 250ms and is not still running event handlers for such an event, then the user agent must queue a task to fire a simple event named timeupdate at the element. (In the other cases, such as explicit seeks, relevant events get fired as part of the overall process of changing the current playback position.)

    The event thus is not to be fired faster than about 66Hz or slower than 4Hz (assuming the event handlers don’t take longer than 250ms to run). User agents are encouraged to vary the frequency of the event based on the system load and the average cost of processing the event each time, so that the UI updates are not any more frequent than the user agent can comfortably handle while decoding the video.

  7. If all of the cues in current cues have their text track cue active flag set, none of the cues in other cues have their text track cue active flag set, and missed cues is empty, then abort these steps.
  8. If the time was reached through the usual monotonic increase of the current playback position during normal playback, and there are cues in other cues that have their text track cue pause-on-exit flag set and that either have their text track cue active flag set or are also in missed cues, then immediately pause the media element.

    In the other cases, such as explicit seeks, playback is not paused by going past the end time of a cue, even if that cue has its text track cue pause-on-exit flag set.

  9. Let events be a list of tasks, initially empty. Each task in this list will be associated with a text track, a text track cue, and a time, which are used to sort the list before the tasks are queued.

    Let affected tracks be a list of text tracks, initially empty.

    When the steps below say to prepare an event named event for a text track cue target with a time time, the user agent must run these substeps:

    1. Let track be the text track with which the text track cue target is associated.
    2. Create a task to fire a simple event named event at target.
    3. Add the newly created task to events, associated with the time time, the text track track, and the text track cue target.
    4. Add track to affected tracks.
  10. For each text track cue in missed cues, prepare an event named enter for the TextTrackCue object with the text track cue start time.
  11. For each text track cue in other cues that either has its text track cue active flag set or is in missed cues, prepare an event named exit for the TextTrackCue object with the later of the text track cue end time and the text track cue start time.
  12. For each text track cue in current cues that does not have its text track cue active flag set, prepare an event named enter for the TextTrackCue object with the text track cue start time.
  13. Sort the tasks in events in ascending time order (tasks with earlier times first).

    Further sort tasks in events that have the same time by the relative text track cue order of the text track cues associated with these tasks.

    Finally, sort tasks in events that have the same time and same text track cue order by placing tasks that fire enter events before those that fire exit events.

  14. Queue each task in events, in list order.
  15. Sort affected tracks in the same order as the text tracks appear in the media element’s list of text tracks, and remove duplicates.
  16. For each text track in affected tracks, in the list order, queue a task to fire a simple event named cuechange at the TextTrack object, and, if the text track has a corresponding track element, to then fire a simple event named cuechange at the track element as well.
  17. Set the text track cue active flag of all the cues in the current cues, and unset the text track cue active flag of all the cues in the other cues.
  18. Run the rules for updating the text track rendering of each of the text tracks in affected tracks that are showing, providing the text track’s text track language as the fallback language if it is not the empty string. For example, for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

For the purposes of the algorithm above, a text track cue is considered to be part of a text track only if it is listed in the text track list of cues, not merely if it is associated with the text track.

If the media element’s node document stops being a fully active document, then the playback will stop until the document is active again.

When a media element is removed from a Document, the user agent must run the following steps:

  1. Await a stable state, allowing the task that removed the media element from the Document to continue. The synchronous section consists of all the remaining steps of this algorithm. (Steps in the synchronous section are marked with ⌛.)
  2. ⌛ If the media element is in a Document, abort these steps.
  3. ⌛ Run the internal pause steps for the media element.
4.7.14.9. Seeking
media . seeking

Returns true if the user agent is currently seeking.

media . seekable

Returns a TimeRanges object that represents the ranges of the media resource to which it is possible for the user agent to seek.

media . fastSeek( time )

Seeks to near the given time as fast as possible, trading precision for speed. (To seek to a precise time, use the currentTime attribute.)

This does nothing if the media resource has not been loaded.

The seeking attribute must initially have the value false.

The fastSeek() method must seek to the time given by the method’s argument, with the approximate-for-speed flag set.

When the user agent is required to seek to a particular new playback position in the media resource, optionally with the approximate-for-speed flag set, it means that the user agent must run the following steps. This algorithm interacts closely with the event loop mechanism; in particular, it has a synchronous section (which is triggered as part of the event loop algorithm). Steps in that section are marked with ⌛.

  1. Set the media element’s show poster flag to false.
  2. If the media element’s readyState is HAVE_NOTHING, abort these steps.
  3. If the element’s seeking IDL attribute is true, then another instance of this algorithm is already running. Abort that other instance of the algorithm without waiting for the step that it is running to complete.
  4. Set the seeking IDL attribute to true.
  5. If the seek was in response to a DOM method call or setting of an IDL attribute, then continue the script. The remainder of these steps must be run in parallel. With the exception of the steps marked with ⌛, they could be aborted at any time by another instance of this algorithm being invoked.
  6. If the new playback position is later than the end of the media resource, then let it be the end of the media resource instead.
  7. If the new playback position is less than the earliest possible position, let it be that position instead.
  8. If the (possibly now changed) new playback position is not in one of the ranges given in the seekable attribute, then let it be the position in one of the ranges given in the seekable attribute that is the nearest to the new playback position. If two positions both satisfy that constraint (i.e., the new playback position is exactly in the middle between two ranges in the seekable attribute) then use the position that is closest to the current playback position. If there are no ranges given in the seekable attribute then set the seeking IDL attribute to false and abort these steps.
  9. If the approximate-for-speed flag is set, adjust the new playback position to a value that will allow for playback to resume promptly. If new playback position before this step is before current playback position, then the adjusted new playback position must also be before the current playback position. Similarly, if the new playback position before this step is after current playback position, then the adjusted new playback position must also be after the current playback position.

    For example, the user agent could snap to a nearby key frame, so that it doesn’t have to spend time decoding then discarding intermediate frames before resuming playback.

  10. Queue a task to fire a simple event named seeking at the element.
  11. Set the current playback position to the new playback position.

    If the media element was potentially playing immediately before it started seeking, but seeking caused its readyState attribute to change to a value lower than HAVE_FUTURE_DATA, then a waiting event will be fired at the element.

    This step sets the current playback position, and thus can immediately trigger other conditions, such as the rules regarding when playback "reaches the end of the media resource" (part of the logic that handles looping), even before the user agent is actually able to render the media data for that position (as determined in the next step).

    The currentTime attribute returns the official playback position, not the current playback position, and therefore gets updated before script execution, separate from this algorithm.

  12. Wait until the user agent has established whether or not the media data for the new playback position is available, and, if it is, until it has decoded enough data to play back that position.
  13. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm. (Steps in the synchronous section are marked with ⌛.)
  14. ⌛ Set the seeking IDL attribute to false.
  15. ⌛ Run the time marches on steps.
  16. Queue a task to fire a simple event named timeupdate at the element.
  17. Queue a task to fire a simple event named seeked at the element.

The seekable attribute must return a new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent is able to seek to, at the time the attribute is evaluated.

If the user agent can seek to anywhere in the media resource, e.g., because it is a simple movie file and the user agent and the server support HTTP Range requests, then the attribute would return an object with one range, whose start is the time of the first frame (the earliest possible position, typically zero), and whose end is the same as the time of the first frame plus the duration attribute’s value (which would equal the time of the last frame, and might be positive Infinity).

The range might be continuously changing, e.g., if the user agent is buffering a sliding window on an infinite stream. This is the behavior seen with DVRs viewing live TV, for instance.

User agents should adopt a very liberal and optimistic view of what is seekable. User agents should also buffer recent content where possible to enable seeking to be fast.

For instance, consider a large video file served on an HTTP server without support for HTTP Range requests. A browser could implement this by only buffering the current frame and data obtained for subsequent frames, never allow seeking, except for seeking to the very start by restarting the playback. However, this would be a poor implementation. A high quality implementation would buffer the last few minutes of content (or more, if sufficient storage space is available), allowing the user to jump back and rewatch something surprizing without any latency, and would in addition allow arbitrary seeking by reloading the file from the start if necessary, which would be slower but still more convenient than having to literally restart the video and watch it all the way through just to get to an earlier unbuffered spot.

Media resources might be internally scripted or interactive. Thus, a media element could play in a non-linear fashion. If this happens, the user agent must act as if the algorithm for seeking was used whenever the current playback position changes in a discontinuous fashion (so that the relevant events fire).

4.7.14.10. Media resources with multiple media tracks

A media resource can have multiple embedded audio and video tracks. For example, in addition to the primary video and audio tracks, a media resource could have foreign-language dubbed dialogs, director’s commentaries, audio descriptions, alternative angles, or sign-language overlays.

media . audioTracks

Returns an AudioTrackList object representing the audio tracks available in the media resource.

media . videoTracks

Returns a VideoTrackList object representing the video tracks available in the media resource.

The audioTracks attribute of a media element must return a live AudioTrackList object representing the audio tracks available in the media element’s media resource.

The videoTracks attribute of a media element must return a live VideoTrackList object representing the video tracks available in the media element’s media resource.

There are only ever one AudioTrackList object and one VideoTrackList object per media element, even if another media resource is loaded into the element: the objects are reused. (The AudioTrack and VideoTrack objects are not, though.)

In this example, a script defines a function that takes a URL to a video and a reference to an element where the video is to be placed. That function then tries to load the video, and, once it is loaded, checks to see if there is a sign-language track available. If there is, it also displays that track. Both tracks are just placed in the given container; it’s assumed that styles have been applied to make this work in a pretty way!
<script>
  function loadVideo(url, container) {
    var video = document.createElement('video');
    video.src = url;
    video.autoplay = true;
    video.controls = true;
    container.appendChild(video);
    video.onloadedmetadata = function (event) {
      for (var i = 0; i < video.videoTracks.length; i += 1) {
        if (video.videoTracks[i].kind == 'sign') {
          var sign = document.createElement('video');
          sign.src = url + '#track=' + video.videoTracks[i].id;
          sign.autoplay = true;
          container.appendChild(sign);
          return;
        }
      }
    };
  }
</script>
4.7.14.10.1. AudioTrackList and VideoTrackList objects

The AudioTrackList and VideoTrackList interfaces are used by attributes defined in the previous section.

interface AudioTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter AudioTrack (unsigned long index);
  AudioTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
interface AudioTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean enabled;
};
interface VideoTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter VideoTrack (unsigned long index);
  VideoTrack? getTrackById(DOMString id);
  readonly attribute long selectedIndex;

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
interface VideoTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean selected;
};
media . audioTracks . length
media . videoTracks . length

Returns the number of tracks in the list.

audioTrack = media . audioTracks[index]
videoTrack = media . videoTracks[index]

Returns the specified AudioTrack or VideoTrack object.

audioTrack = media . audioTracks . getTrackById( id )
videoTrack = media . videoTracks . getTrackById( id )

Returns the AudioTrack or VideoTrack object with the given identifier, or null if no track has that identifier.

audioTrack . id
videoTrack . id

Returns the ID of the given track. This is the ID that can be used with a fragment identifier if the format supports the Media Fragments URI syntax, and that can be used with the getTrackById() method. [MEDIA-FRAGS]

audioTrack . kind
videoTrack . kind

Returns the category the given track falls into. The possible track categories are given below.

audioTrack . label
videoTrack . label

Returns the label of the given track, if known, or the empty string otherwise.

audioTrack . language
videoTrack . language

Returns the language of the given track, if known, or the empty string otherwise.

audioTrack . enabled [ = value ]

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is enabled or not. If multiple audio tracks are enabled simultaneously, they are mixed.

media . videoTracks . selectedIndex

Returns the index of the currently selected track, if any, or -1 otherwise.

videoTrack . selected [ = value ]

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is selected or not. Either zero or one video track is selected; selecting a new track while a previous one is selected will unselect the previous one.

An AudioTrackList object represents a dynamic list of zero or more audio tracks, of which zero or more can be enabled at a time. Each audio track is represented by an AudioTrack object.

A VideoTrackList object represents a dynamic list of zero or more video tracks, of which zero or one can be selected at a time. Each video track is represented by a VideoTrack object.

Tracks in AudioTrackList and VideoTrackList objects must be consistently ordered. If the media resource is in a format that defines an order, then that order must be used; otherwise, the order must be the relative order in which the tracks are declared in the media resource. The order used is called the natural order of the list.

Each track in one of these objects thus has an index; the first has the index 0, and each subsequent track is numbered one higher than the previous one. If a media resource dynamically adds or removes audio or video tracks, then the indices of the tracks will change dynamically. If the media resource changes entirely, then all the previous tracks will be removed and replaced with new tracks.

The AudioTrackList.length and VideoTrackList.length attributes must return the number of tracks represented by their objects at the time of getting.

The supported property indices of AudioTrackList and VideoTrackList objects at any instant are the numbers from zero to the number of tracks represented by the respective object minus one, if any tracks are represented. If an AudioTrackList or VideoTrackList object represents no tracks, it has no supported property indices.

To determine the value of an indexed property for a given index index in an AudioTrackList or VideoTrackList object list, the user agent must return the AudioTrack or VideoTrack object that represents the indexth track in list.

The AudioTrackList.getTrackById(id) and VideoTrackList.getTrackById(id) methods must return the first AudioTrack or VideoTrack object (respectively) in the AudioTrackList or VideoTrackList object (respectively) whose identifier is equal to the value of the id argument (in the natural order of the list, as defined above). When no tracks match the given argument, the methods must return null.

The AudioTrack and VideoTrack objects represent specific tracks of a media resource. Each track can have an identifier, category, label, and language. These aspects of a track are permanent for the lifetime of the track; even if a track is removed from a media resource’s AudioTrackList or VideoTrackList objects, those aspects do not change.

In addition, AudioTrack objects can each be enabled or disabled; this is the audio track’s enabled state. When an AudioTrack is created, its enabled state must be set to false (disabled). The resource fetch algorithm can override this.

Similarly, a single VideoTrack object per VideoTrackList object can be selected, this is the video track’s selection state. When a VideoTrack is created, its selection state must be set to false (not selected). The resource fetch algorithm can override this.

The AudioTrack.id and VideoTrack.id attributes must return the identifier of the track, if it has one, or the empty string otherwise. If the media resource is in a format that supports the Media Fragments URI fragment identifier syntax, the identifier returned for a particular track must be the same identifier that would enable the track if used as the name of a track in the track dimension of such a fragment identifier. [MEDIA-FRAGS] [INBANDTRACKS]

For example, in Ogg files, this would be the Name header field of the track. [OGGSKELETON]

The AudioTrack.kind and VideoTrack.kind attributes must return the category of the track, if it has one, or the empty string otherwise.

The category of a track is the string given in the first column of the table below that is the most appropriate for the track based on the definitions in the table’s second and third columns, as determined by the metadata included in the track in the media resource. The cell in the third column of a row says what the category given in the cell in the first column of that row applies to; a category is only appropriate for an audio track if it applies to audio tracks, and a category is only appropriate for video tracks if it applies to video tracks. Categories must only be returned for AudioTrack objects if they are appropriate for audio, and must only be returned for VideoTrack objects if they are appropriate for video.

Return values for AudioTrack.kind and VideoTrack.kind
Category Definition Applies to...
"alternative" A possible alternative to the main track, e.g., a different take of a song (audio), or a different angle (video). Audio and video.
"captions" A version of the main video track with captions burnt in. (For legacy content; new content would use text tracks.) Video only.
"descriptions" An audio description of a video track. Audio only.
"main" The primary audio or video track. Audio and video.
"main-desc" The primary audio track, mixed with audio descriptions. Audio only.
"sign" A sign-language interpretation of an audio track. Video only.
"subtitles" A version of the main video track with subtitles burnt in. (For legacy content; new content would use text tracks.) Video only.
"translation" A translated version of the main audio track. Audio only.
"commentary" Commentary on the primary audio or video track, e.g., a director’s commentary. Audio and video.
"" (empty string) No explicit kind, or the kind given by the track’s metadata is not recognized by the user agent. Audio and video.

The AudioTrack.label and VideoTrack.label attributes must return the label of the track, if it has one, or the empty string otherwise. [INBANDTRACKS]

The AudioTrack.language and VideoTrack.language attributes must return the BCP 47 language tag of the language of the track, if it has one, or the empty string otherwise. If the user agent is not able to express that language as a BCP 47 language tag (for example because the language information in the media resource’s format is a free-form string without a defined interpretation), then the method must return the empty string, as if the track had no language.

Source attribute values for id, kind, label and language of multitrack audio and video tracks as described for the relevant media resource format. [INBANDTRACKS]

The AudioTrack.enabled attribute, on getting, must return true if the track is currently enabled, and false otherwise. On setting, it must enable the track if the new value is true, and disable it otherwise. (If the track is no longer in an AudioTrackList object, then the track being enabled or disabled has no effect beyond changing the value of the attribute on the AudioTrack object.)

Whenever an audio track in an AudioTrackList that was disabled is enabled, and whenever one that was enabled is disabled, the user agent must queue a task to fire a simple event named change at the AudioTrackList object.

An audio track that has no data for a particular position on the media timeline, or that does not exist at that position, must be interpreted as being silent at that point on the timeline.

The VideoTrackList.selectedIndex attribute must return the index of the currently selected track, if any. If the VideoTrackList object does not currently represent any tracks, or if none of the tracks are selected, it must instead return -1.

The VideoTrack.selected attribute, on getting, must return true if the track is currently selected, and false otherwise. On setting, it must select the track if the new value is true, and unselect it otherwise. If the track is in a VideoTrackList, then all the other VideoTrack objects in that list must be unselected. (If the track is no longer in a VideoTrackList object, then the track being selected or unselected has no effect beyond changing the value of the attribute on the VideoTrack object.)

Whenever a track in a VideoTrackList that was previously not selected is selected, and whenever the selected track in a VideoTrackList is unselected without a new track being selected in its stead, the user agent must queue a task to fire a simple event named change at the VideoTrackList object. This task must be queued before the task that fires the resize event, if any.

A video track that has no data for a particular position on the media timeline must be interpreted as being fully transparent black at that point on the timeline, with the same dimensions as the last frame before that position, or, if the position is before all the data for that track, the same dimensions as the first frame for that track. A track that does not exist at all at the current position must be treated as if it existed but had no data.

For instance, if a video has a track that is only introduced after one hour of playback, and the user selects that track then goes back to the start, then the user agent will act as if that track started at the start of the media resource but was simply transparent until one hour in.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the AudioTrackList and VideoTrackList interfaces:

Event handler Event handler event type
onchange change
onaddtrack addtrack
onremovetrack removetrack
4.7.14.10.2. Selecting specific audio and video tracks declaratively

The audioTracks and videoTracks attributes allow scripts to select which track should play, but it is also possible to select specific tracks declaratively, by specifying particular tracks in the fragment identifier of the URL of the media resource. The format of the fragment identifier depends on the MIME type of the media resource. [RFC2046] [URL]

In this example, a video that uses a format that supports the Media Fragments URI fragment identifier syntax is embedded in such a way that the alternative angles labeled "Alternative" are enabled instead of the default video track. [MEDIA-FRAGS]
<video src="myvideo#track=Alternative"></video>
4.7.14.11. Timed text tracks
4.7.14.11.1. Text track model

A media element can have a group of associated text tracks, known as the media element’s list of text tracks. The text tracks are sorted as follows:

  1. The text tracks corresponding to track element children of the media element, in tree order.
  2. Any text tracks added using the addTextTrack() method, in the order they were added, oldest first.
  3. Any media-resource-specific text tracks (text tracks corresponding to data in the media resource), in the order defined by the media resource’s format specification.

A text track consists of:

The kind of text track

This decides how the track is handled by the user agent. The kind is represented by a string. The possible strings are:

  • subtitles
  • captions
  • descriptions
  • chapters
  • metadata

The kind of track can change dynamically, in the case of a text track corresponding to a track element.

A label

This is a human-readable string intended to identify the track for the user.

The label of a track can change dynamically, in the case of a text track corresponding to a track element.

When a text track label is the empty string, the user agent should automatically generate an appropriate label from the text track’s other properties (e.g., the kind of text track and the text track’s language) for use in its user interface. This automatically-generated label is not exposed in the API.

An in-band metadata track dispatch type

This is a string extracted from the media resource specifically for in-band metadata tracks to enable such tracks to be dispatched to different scripts in the document.

For example, a traditional TV station broadcast streamed on the Web and augmented with Web-specific interactive features could include text tracks with metadata for ad targeting, trivia game data during game shows, player states during sports games, recipe information during food programs, and so forth. As each program starts and ends, new tracks might be added or removed from the stream, and as each one is added, the user agent could bind them to dedicated script modules using the value of this attribute.

Other than for in-band metadata text tracks, the in-band metadata track dispatch type is the empty string. How this value is populated for different media formats is described in steps to expose a media-resource-specific text track.

A language

This is a string (a BCP 47 language tag) representing the language of the text track’s cues. [BCP47]

The language of a text track can change dynamically, in the case of a text track corresponding to a track element.

A readiness state

One of the following:

Not loaded

Indicates that the text track’s cues have not been obtained.

Loading

Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track by the parser.

Loaded

Indicates that the text track has been loaded with no fatal errors.

Failed to load

Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g., URL could not be resolved, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained.

The readiness state of a text track changes dynamically as the track is obtained.

A mode

One of the following:

Disabled

Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. No cues are active, no events are fired, and the user agent will not attempt to obtain the track’s cues.

Hidden

Indicates that the text track is active, but that the user agent is not actively displaying the cues. If no attempt has yet been made to obtain the track’s cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly.

Showing

Indicates that the text track is active. If no attempt has yet been made to obtain the track’s cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly. In addition, for text tracks whose kind is subtitles or captions, the cues are being overlaid on the video as appropriate; for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue.

A list of zero or more cues

A list of text track cues, along with rules for updating the text track rendering. For example, for WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The list of cues of a text track can change dynamically, either because the text track has not yet been loaded or is still loading, or due to DOM manipulation.

Each text track has a corresponding TextTrack object.


Each media element has a list of pending text tracks, which must initially be empty, a blocked-on-parser flag, which must initially be false, and a did-perform-automatic-track-selection flag, which must also initially be false.

When the user agent is required to populate the list of pending text tracks of a media element, the user agent must add to the element’s list of pending text tracks each text track in the element’s list of text tracks whose text track mode is not disabled and whose text track readiness state is loading.

Whenever a track element’s parent node changes, the user agent must remove the corresponding text track from any list of pending text tracks that it is in.

Whenever a text track’s text track readiness state changes to either loaded or failed to load, the user agent must remove it from any list of pending text tracks that it is in.

When a media element is created by an HTML parser or XML parser, the user agent must set the element’s blocked-on-parser flag to true. When a media element is popped off the stack of open elements of an HTML parser or XML parser, the user agent must honor user preferences for automatic text track selection, populate the list of pending text tracks, and set the element’s blocked-on-parser flag to false.

The text tracks of a media element are ready when both the element’s list of pending text tracks is empty and the element’s blocked-on-parser flag is false.

Each media element has a pending text track change notification flag, which must initially be unset.

Whenever a text track that is in a media element’s list of text tracks has its text track mode change value, the user agent must run the following steps for the media element:

  1. If the media element’s pending text track change notification flag is set, abort these steps.
  2. Set the media element’s pending text track change notification flag.
  3. Queue a task that runs the following substeps:

    1. Unset the media element’s pending text track change notification flag.
    2. Fire a simple event named change at the media element’s textTracks attribute’s TextTrackList object.
  4. If the media element’s show poster flag is not set, run the time marches on steps.

The task source for the tasks listed in this section is the DOM manipulation task source.


A text track cue is the unit of time-sensitive data in a text track, corresponding for instance for subtitles and captions to the text that appears at a particular time and disappears at another time.

Each text track cue consists of:

An identifier
An arbitrary string.
A start time
The time, in seconds and fractions of a second, that describes the beginning of the range of the media data to which the cue applies.
An end time
The time, in seconds and fractions of a second, that describes the end of the range of the media data to which the cue applies.
A pause-on-exit flag
A boolean indicating whether playback of the media resource is to pause when the end of the range to which the cue applies is reached.
Some additional format-specific data
Additional fields, as needed for the format. For example, WebVTT has a text track cue writing direction and so forth. [WEBVTT]
Rules for extracting the chapter title
An algorithm which, when applied to the cue, returns a string that can be used in user interfaces that use the cue as a chapter title.

The text track cue start time and text track cue end time can be negative. (The current playback position can never be negative, though, so cues entirely before time zero cannot be active.)

Each text track cue has a corresponding TextTrackCue object (or more specifically, an object that inherits from TextTrackCue — for example, WebVTT cues use the VTTCue interface). A text track cue’s in-memory representation can be dynamically changed through this TextTrackCue API. [WEBVTT]

A text track cue is associated with rules for updating the text track rendering, as defined by the specification for the specific kind of text track cue. These rules are used specifically when the object representing the cue is added to a TextTrack object using the addCue() method.

In addition, each text track cue has two pieces of dynamic information:

The active flag

This flag must be initially unset. The flag is used to ensure events are fired appropriately when the cue becomes active or inactive, and to make sure the right cues are rendered.

The user agent must immediately unset this flag whenever the text track cue is removed from its text track’s text track list of cues; whenever the text track itself is removed from its media element’s list of text tracks or has its text track mode changed to disabled; and whenever the media element’s readyState is changed back to HAVE_NOTHING. When the flag is unset in this way for one or more cues in text tracks that were showing prior to the relevant incident, the user agent must, after having unset the flag for all the affected cues, apply the rules for updating the text track rendering of those text tracks. For example, for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The display state

This is used as part of the rendering model, to keep cues in a consistent position. It must initially be empty. Whenever the text track cue active flag is unset, the user agent must empty the text track cue display state.

The text track cues of a media element’s text tracks are ordered relative to each other in the text track cue order, which is determined as follows: first group the cues by their text track, with the groups being sorted in the same order as their text tracks appear in the media element’s list of text tracks; then, within each group, cues must be sorted by their start time, earliest first; then, any cues with the same start time must be sorted by their end time, latest first; and finally, any cues with identical end times must be sorted in the order they were last added to their respective text track list of cues, oldest first (so e.g., for cues from a WebVTT file, that would initially be the order in which the cues were listed in the file). [WEBVTT]

4.7.14.11.2. Sourcing in-band text tracks

A media-resource-specific text track is a text track that corresponds to data found in the media resource.

Rules for processing and rendering such data are defined by the relevant specifications, e.g., the specification of the video format if the media resource is a video. Details for some legacy formats can be found in the Sourcing In-band Media Resource Tracks from Media Containers into HTML specification. [INBANDTRACKS]

When a media resource contains data that the user agent recognizes and supports as being equivalent to a text track, the user agent runs the steps to expose a media-resource-specific text track with the relevant data, as follows.

  1. Associate the relevant data with a new text track and its corresponding new TextTrack object. The text track is a media-resource-specific text track.
  2. Set the new text track’s kind, label, and language based on the semantics of the relevant data, as defined for the relevant format [INBANDTRACKS]. If there is no label in that data, then the label must be set to the empty string.
  3. Associate the text track list of cues with the rules for updating the text track rendering appropriate for the format in question.
  4. If the new text track’s kind is metadata, then set the text track in-band metadata track dispatch type as follows, based on the type of the media resource:

    If the media resource is an Ogg file
    The text track in-band metadata track dispatch type must be set to the value of the Role header field. [OGGSKELETON]
    If the media resource is a WebM file
    The text track in-band metadata track dispatch type must be set to the value of the CodecID element. [WEBM]
    If the media resource is an MPEG-2 file
    Let stream type be the value of the "stream_type" field describing the text track’s type in the file’s program map section, interpreted as an 8-bit unsigned integer. Let length be the value of the "ES_info_length" field for the track in the same part of the program map section, interpreted as an integer as defined by the MPEG-2 specification. Let descriptor bytes be the length bytes following the "ES_info_length" field. The text track in-band metadata track dispatch type must be set to the concatenation of the stream type byte and the zero or more descriptor bytes bytes, expressed in hexadecimal using uppercase ASCII hex digits. [MPEG2TS]
    If the media resource is an MPEG-4 file
    Let the first stsd box of the first stbl box of the first minf box of the first mdia box of the text track’s trak box in the first moov box of the file be the stsd box, if any.

    If the file has no stsd box, or if the stsd box has neither a mett box nor a metx box, then the text track in-band metadata track dispatch type must be set to the empty string.

    Otherwise, if the stsd box has a mett box then the text track in-band metadata track dispatch type must be set to the concatenation of the string "mett", a U+0020 SPACE character, and the value of the first mime_format field of the first mett box of the stsd box, or the empty string if that field is absent in that box.

    Otherwise, if the stsd box has no mett box but has a metx box then the text track in-band metadata track dispatch type must be set to the concatenation of the string "metx", a U+0020 SPACE character, and the value of the first namespace field of the first metx box of the stsd box, or the empty string if that field is absent in that box.

    [MPEG4]

    If the media resource is a DASH media resource
    The text track in-band metadata track dispatch type must be set to the concatenation of the "AdaptationSet" element attributes and all child Role descriptors. [MPEGDASH]
  5. Populate the new text track’s list of cues with the cues parsed so far, following the guidelines for exposing cues, and begin updating it dynamically as necessary.
  6. Set the new text track’s readiness state to loaded.
  7. Set the new text track’s mode to the mode consistent with the user’s preferences and the requirements of the relevant specification for the data.

    For instance, if there are no other active subtitles, and this is a forced subtitle track (a subtitle track giving subtitles in the audio track’s primary language, but only for audio that is actually in another language), then those subtitles might be activated here.

  8. Add the new text track to the media element’s list of text tracks.
  9. Fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.
4.7.14.11.3. Sourcing out-of-band text tracks

When a track element is created, it must be associated with a new text track (with its value set as defined below) and its corresponding new TextTrack object.

The text track kind is determined from the state of the element’s kind attribute according to the following table; for a state given in a cell of the first column, the kind is the string given in the second column:

State String
Subtitles subtitles
Captions captions
Descriptions descriptions
Chapters chapters
Metadata metadata

The text track label is the element’s track label.

The text track language is the element’s track language, if any, or the empty string otherwise.

As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly, as per the definitions above.

Changes to the track URL are handled in the algorithm below.

The text track readiness state is initially not loaded, and the text track mode is initially disabled.

The text track list of cues is initially empty. It is dynamically modified when the referenced file is parsed. Associated with the list are the rules for updating the text track rendering appropriate for the format in question; for WebVTT, this is the rules for updating the display of WebVTT text tracks. [WEBVTT]

When a track element’s parent element changes and the new parent is a media element, then the user agent must add the track element’s corresponding text track to the media element’s list of text tracks, and then queue a task to fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.

When a track element’s parent element changes and the old parent was a media element, then the user agent must remove the track element’s corresponding text track from the media element’s list of text tracks, and then queue a task to fire a trusted event with the name removetrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.


When a text track corresponding to a track element is added to a media element’s list of text tracks, the user agent must queue a task to run the following steps for the media element:

  1. If the element’s blocked-on-parser flag is true, abort these steps.
  2. If the element’s did-perform-automatic-track-selection flag is true, abort these steps.
  3. Honor user preferences for automatic text track selection for this element.

When the user agent is required to honor user preferences for automatic text track selection for a media element, the user agent must run the following steps:

  1. Perform automatic text track selection for subtitles and captions.
  2. Perform automatic text track selection for descriptions.
  3. Perform automatic text track selection for chapters.
  4. If there are any text tracks in the media element’s list of text tracks whose text track kind is metadata that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of all such tracks to hidden
  5. Set the element’s did-perform-automatic-track-selection flag to true.

When the steps above say to perform automatic text track selection for one or more text track kinds, it means to run the following steps:

  1. Let candidates be a list consisting of the text tracks in the media element’s list of text tracks whose text track kind is one of the kinds that were passed to the algorithm, if any, in the order given in the list of text tracks.
  2. If candidates is empty, then abort these steps.
  3. If any of the text tracks in candidates have a text track mode set to showing, abort these steps.
  4. If the user has expressed an interest in having a track from candidates enabled based on its text track kind, text track language, and text track label, then set its text track mode to showing.

    For example, the user could have set a browser preference to the effect of "I want French captions whenever possible", or "If there is a subtitle track with "Commentary" in the title, enable it", or "If there are audio description tracks available, enable one, ideally in Swiss German, but failing that in Standard Swiss German or Standard German".

    Otherwise, if there are any text tracks in candidates that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of the first such track to showing.

When a text track corresponding to a track element experiences any of the following circumstances, the user agent must start the track processing model for that text track and its track element:

When a user agent is to start the track processing model for a text track and its track element, it must run the following algorithm. This algorithm interacts closely with the event loop mechanism; in particular, it has a synchronous section (which is triggered as part of the event loop algorithm). The steps in that section are marked with ⌛.

  1. If another occurrence of this algorithm is already running for this text track and its track element, abort these steps, letting that other algorithm take care of this element.
  2. If the text track’s text track mode is not set to one of hidden or showing, abort these steps.
  3. If the text track’s track element does not have a media element as a parent, abort these steps.
  4. Run the remainder of these steps in parallel, allowing whatever caused these steps to run to continue.
  5. Top: Await a stable state. The synchronous section consists of the following steps. (The steps in the synchronous section are marked with ⌛.)
  6. ⌛ Set the text track readiness state to loading.
  7. ⌛ Let URL be the track URL of the track element.
  8. ⌛ If the track element’s parent is a media element then let corsAttributeState be the state of the parent media element’s crossorigin content attribute. Otherwise, let corsAttributeState be No CORS.
  9. End the synchronous section, continuing the remaining steps in parallel.
  10. If URL is not the empty string, run these substeps:

    1. Let request be the result of creating a potential-CORS request given URL, corsAttributeState, and with the same-origin fallback flag set.
    2. Set request’s client to the track element’s node document’s Window object’s environment settings object and type to "track".
    3. Fetch request.

    The tasks queued by the fetching algorithm on the networking task source to process the data as it is being fetched must determine the type of the resource. If the type of the resource is not a supported text track format, the load will fail, as described below. Otherwise, the resource’s data must be passed to the appropriate parser (e.g., the WebVTT parser) as it is received, with the text track list of cues being used for that parser’s output. [WEBVTT]

    The appropriate parser will incrementally update the text track list of cues during these networking task source tasks, as each such task is run with whatever data has been received from the network).

    This specification does not currently say whether or how to check the MIME types of text tracks, or whether or how to perform file type sniffing using the actual file data. Implementors differ in their intentions on this matter and it is therefore unclear what the right solution is. In the absence of any requirement here, the HTTP specification’s strict requirement to follow the Content-Type header prevails ("Content-Type specifies the media type of the underlying data." ... "If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource.").

    If the fetching algorithm fails for any reason (network error, the server returns an error code, a cross-origin check fails, etc), or if URL is the empty string, then queue a task to first change the text track readiness state to failed to load and then fire a simple event named error at the track element. This task must use the DOM manipulation task source.

    If the fetching algorithm does not fail, but the type of the resource is not a supported text track format, or the file was not successfully processed (e.g., the format in question is an XML format and the file contained a well-formedness error that the XML specification requires be detected and reported to the application), then the task that is queued by the networking task source in which the aforementioned problem is found must change the text track readiness state to failed to load and fire a simple event named error at the track element.

    If the fetching algorithm does not fail, and the file was successfully processed, then the final task that is queued by the networking task source, after it has finished parsing the data, must change the text track readiness state to loaded, and fire a simple event named load at the track element.

    If, while fetching is ongoing, either:

    ...then the user agent must abort fetching, discarding any pending tasks generated by that algorithm (and in particular, not adding any cues to the text track list of cues after the moment the URL changed), and then queue a task that first changes the text track readiness state to failed to load and then fires a simple event named error at the track element. This task must use the DOM manipulation task source.

  11. Wait until the text track readiness state is no longer set to loading.
  12. Wait until the track URL is no longer equal to URL, at the same time as the text track mode is set to hidden or showing.
  13. Jump to the step labeled top.

Whenever a track element has its src attribute set, changed, or removed, the user agent must immediately empty the element’s text track’s text track list of cues. (This also causes the algorithm above to stop adding cues from the resource being obtained using the previously given URL, if any.)

4.7.14.11.4. Guidelines for exposing cues in various formats as text track cues

How a specific format’s text track cues are to be interpreted for the purposes of processing by an HTML user agent is defined by that format [INBANDTRACKS]. In the absence of such a specification, this section provides some constraints within which implementations can attempt to consistently expose such formats.

To support the text track model of HTML, each unit of timed data is converted to a text track cue. Where the mapping of the format’s features to the aspects of a text track cue as defined in this specification are not defined, implementations must ensure that the mapping is consistent with the definitions of the aspects of a text track cue as defined above, as well as with the following constraints:

The text track cue identifier
Should be set to the empty string if the format has no obvious analog to a per-cue identifier.
The text track cue pause-on-exit flag
Should be set to false.

For media-resource-specific text tracks of kind metadata, text track cues are exposed using the DataCue object unless there is a more appropriate TextTrackCue interface available. For example, if the media-resource-specific text track format is WebVTT, then VTTCue is more appropriate.

4.7.14.11.5. Text track API
interface TextTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter TextTrack (unsigned long index);
  TextTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
media . textTracks . length
Returns the number of text tracks associated with the media element (e.g., from track elements). This is the number of text tracks in the media element’s list of text tracks.
media . textTracks[ n ]
Returns the TextTrack object representing the nth text track in the media element’s list of text tracks.
textTrack = media . textTracks . getTrackById( id )

Returns the TextTrack object with the given identifier, or null if no track has that identifier.

A TextTrackList object represents a dynamically updating list of text tracks in a given order.

The textTracks attribute of media elements must return a TextTrackList object representing the TextTrack objects of the text tracks in the media element’s list of text tracks, in the same order as in the list of text tracks.

The length attribute of a TextTrackList object must return the number of text tracks in the list represented by the TextTrackList object.

The supported property indices of a TextTrackList object at any instant are the numbers from zero to the number of text tracks in the list represented by the TextTrackList object minus one, if any. If there are no text tracks in the list, there are no supported property indices.

To determine the value of an indexed property of a TextTrackList object for a given index index, the user agent must return the indexth text track in the list represented by the TextTrackList object.

The getTrackById(id) method must return the first TextTrack in the TextTrackList object whose id IDL attribute would return a value equal to the value of the id argument. When no tracks match the given argument, the method must return null.


enum TextTrackMode { "disabled",  "hidden",  "showing" };

enum TextTrackKind { "subtitles",  "captions",  "descriptions",  "chapters",  "metadata" };

interface TextTrack : EventTarget {
  readonly attribute TextTrackKind kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;

  readonly attribute DOMString id;
  readonly attribute DOMString inBandMetadataTrackDispatchType;

  attribute TextTrackMode mode;

  readonly attribute TextTrackCueList? cues;
  readonly attribute TextTrackCueList? activeCues;

  void addCue(TextTrackCue cue);
  void removeCue(TextTrackCue cue);

  attribute EventHandler oncuechange;
};
textTrack = media . addTextTrack( kind [, label [, language ] ] )

Creates and returns a new TextTrack object, which is also added to the media element’s list of text tracks.

textTrack . kind

Returns the text track kind string.

textTrack . label

Returns the text track label, if there is one, or the empty string otherwise (indicating that a custom label probably needs to be generated from the other attributes of the object if the object is exposed to the user).

textTrack . language
Returns the text track language string.
textTrack . id

Returns the ID of the given track.

For in-band tracks, this is the ID that can be used with a fragment identifier if the format supports the Media Fragments URI syntax, and that can be used with the getTrackById() method. [MEDIA-FRAGS]

For TextTrack objects corresponding to track elements, this is the ID of the track element.

textTrack . inBandMetadataTrackDispatchType

Returns the text track in-band metadata track dispatch type string.

textTrack . mode [ = value ]

Returns the text track mode, represented by a string from the following list:

"disabled"
The text track disabled mode.
"hidden"
The text track hidden mode.
"showing"
The text track showing mode.

Can be set, to change the mode.

textTrack . cues
Returns the text track list of cues, as a TextTrackCueList object.
textTrack . activeCues

Returns the text track cues from the text track list of cues that are currently active (i.e., that start before the current playback position and end after it), as a TextTrackCueList object.

textTrack . addCue( cue )
Adds the given cue to textTrack’s text track list of cues.
textTrack . removeCue( cue )
Removes the given cue from textTrack’s text track list of cues.

The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:

  1. Create a new TextTrack object.

  2. Create a new text track corresponding to the new object, and set its text track kind to kind, its text track label to label, its text track language to language, its text track readiness state to the text track loaded state, its text track mode to the text track hidden mode, and its text track list of cues to an empty list.

    Initially, the text track list of cues is not associated with any rules for updating the text track rendering. When a text track cue is added to it, the text track list of cues has its rules permanently set accordingly.

  3. Add the new text track to the media element’s list of text tracks.

  4. Queue a task to fire a trusted event with the name addtrack, that does not bubble and is not cancelable, and that uses the TrackEvent interface, with the track attribute initialized to the new text track’s TextTrack object, at the media element’s textTracks attribute’s TextTrackList object.

  5. Return the new TextTrack object.


The kind attribute must return the text track kind of the text track that the TextTrack object represents.

The label attribute must return the text track label of the text track that the TextTrack object represents.

The language attribute must return the text track language of the text track that the TextTrack object represents.

The id attribute returns the track’s identifier, if it has one, or the empty string otherwise. For tracks that correspond to track elements, the track’s identifier is the value of the element’s id attribute, if any. For in-band tracks, the track’s identifier is specified by the media resource. If the media resource is in a format that supports the Media Fragments URI fragment identifier syntax, the identifier returned for a particular track must be the same identifier that would enable the track if used as the name of a track in the track dimension of such a fragment identifier. [MEDIA-FRAGS]

The inBandMetadataTrackDispatchType attribute must return the text track in-band metadata track dispatch type of the text track that the TextTrack object represents.

The mode attribute, on getting, must return the string corresponding to the text track mode of the text track that the TextTrack object represents, as defined by the following list:

"disabled"
The text track disabled mode.
"hidden"
The text track hidden mode.
"showing"
The text track showing mode.

On setting, if the new value isn’t equal to what the attribute would currently return, the new value must be processed as follows:

If the new value is "disabled"

Set the text track mode of the text track that the TextTrack object represents to the text track disabled mode.

If the new value is "hidden"

Set the text track mode of the text track that the TextTrack object represents to the text track hidden mode.

If the new value is "showing"

Set the text track mode of the text track that the TextTrack object represents to the text track showing mode.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the cues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose end times occur at or after the earliest possible position when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

The earliest possible position when the script started is whatever the earliest possible position was the last time the event loop reached step 1.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the activeCues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose active flag was set when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

A text track cue’s active flag was set when the script started if its text track cue active flag was set the last time the event loop reached step 1.


The addCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the text track list of cues does not yet have any associated rules for updating the text track rendering, then associate the text track list of cues with the rules for updating the text track rendering appropriate to cue.
  2. If text track list of cues' associated rules for updating the text track rendering are not the same rules for updating the text track rendering as appropriate for cue, then throw an InvalidStateError exception and abort these steps.
  3. If the given cue is in a text track list of cues, then remove cue from that text track list of cues.
  4. Add cue to the method’s TextTrack object’s text track’s text track list of cues.

The removeCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the given cue is not currently listed in the method’s TextTrack object’s text track’s text track list of cues, then throw a NotFoundError exception and abort these steps.
  2. Remove cue from the method’s TextTrack object’s text track’s text track list of cues.
In this example, an audio element is used to play a specific sound-effect from a sound file containing many sound effects. A cue is used to pause the audio, so that it ends exactly at the end of the clip, even if the browser is busy running some script. If the page had relied on script to pause the audio, then the start of the next clip might be heard if the browser was not able to run the script at the exact time specified.
var sfx = new Audio('sfx.wav');
var sounds = sfx.addTextTrack('metadata');

// add sounds we care about
function addFX(start, end, name) {
  var cue = new VTTCue(start, end, '');
  cue.id = name;
  cue.pauseOnExit = true;
  sounds.addCue(cue);
}
addFX(12.783, 13.612, 'dog bark');
addFX(13.612, 15.091, 'kitten mew'))

function playSound(id) {
  sfx.currentTime = sounds.getCueById(id).startTime;
  sfx.play();
}

// play a bark as soon as we can
sfx.oncanplaythrough = function () {
  playSound('dog bark');
}
// meow when the user tries to leave
window.onbeforeunload = function () {
  playSound('kitten mew');
  return 'Are you sure you want to leave this awesome page?';
}

interface TextTrackCueList {
  readonly attribute unsigned long length;
  getter TextTrackCue (unsigned long index);
  TextTrackCue? getCueById(DOMString id);
};
cuelist . length
Returns the number of cues in the list.
cuelist[index]
Returns the text track cue with index index in the list. The cues are sorted in text track cue order.
cuelist . getCueById( id )
Returns the first text track cue (in text track cue order) with text track cue identifier id. Returns null if none of the cues have the given identifier or if the argument is the empty string.

A TextTrackCueList object represents a dynamically updating list of text track cues in a given order.

The length attribute must return the number of cues in the list represented by the TextTrackCueList object.

The supported property indices of a TextTrackCueList object at any instant are the numbers from zero to the number of cues in the list represented by the TextTrackCueList object minus one, if any. If there are no cues in the list, there are no supported property indices.

To determine the value of an indexed property for a given index index, the user agent must return the indexth text track cue in the list represented by the TextTrackCueList object.

The getCueById(id) method, when called with an argument other than the empty string, must return the first text track cue in the list represented by the TextTrackCueList object whose text track cue identifier is id, if any, or null otherwise. If the argument is the empty string, then the method must return null.


interface TextTrackCue : EventTarget {
  readonly attribute TextTrack? track;

  attribute DOMString id;
  attribute double startTime;
  attribute double endTime;
  attribute boolean pauseOnExit;

  attribute EventHandler onenter;
  attribute EventHandler onexit;
};
cue . track
Returns the TextTrack object to which this text track cue belongs, if any, or null otherwise.
cue . id [ = value ]
Returns the text track cue identifier. Can be set.
cue . startTime [ = value ]
Returns the text track cue start time, in seconds. Can be set.
cue . endTime [ = value ]
Returns the text track cue end time, in seconds. Can be set.
cue . pauseOnExit [ = value ]
Returns true if the text track cue pause-on-exit flag is set, false otherwise. Can be set.

The track attribute, on getting, must return the TextTrack object of the text track in whose list of cues the text track cue that the TextTrackCue object represents finds itself, if any; or null otherwise.

The id attribute, on getting, must return the text track cue identifier of the text track cue that the TextTrackCue object represents. On setting, the text track cue identifier must be set to the new value.

The startTime attribute, on getting, must return the text track cue start time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue start time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object’s text track cue is in a text track’s list of cues, and that text track is in a media element’s list of text tracks, and the media element’s show poster flag is not set, then run the time marches on steps for that media element.

The endTime attribute, on getting, must return the text track cue end time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue end time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object’s text track cue is in a text track’s list of cues, and that text track is in a media element’s list of text tracks, and the media element’s show poster flag is not set, then run the time marches on steps for that media element.

The pauseOnExit attribute, on getting, must return true if the text track cue pause-on-exit flag of the text track cue that the TextTrackCue object represents is set; or false otherwise. On setting, the text track cue pause-on-exit flag must be set if the new value is true, and must be unset otherwise.

4.7.14.11.6. Text tracks exposing in-band metadata

The use of text tracks exposing in-band metadata is "at risk". If testing during the Candidate Recommendation phase does not identify at least two interoperable implementations in current shipping browsers of text tracks exposing in-band metadata this section will be removed from the HTML 5.1 Specification.

Media resources often contain one or more media-resource-specific text tracks containing data that browsers don’t render, but want to expose to script to allow being dealt with.

If the browser is unable to identify a TextTrackCue interface that is more appropriate to expose the data in the cues of a media-resource-specific text track, the DataCue object is used. [INBANDTRACKS]

[Constructor(double startTime, double endTime, ArrayBuffer data)]
interface DataCue : TextTrackCue {
  attribute ArrayBuffer data;
};
cue = new DataCue( [ startTime, endTime, data ] )
Returns a new DataCue object, for use with the addCue() method. The startTime argument sets the text track cue start time. The endTime argument sets the text track cue end time. The data argument is copied as the text track cue data.
cue . data [ = value ]
Returns the text track cue data in raw unparsed form. Can be set.

The data attribute, on getting, must return the raw text track cue data of the text track cue that the TextTrackCue object represents. On setting, the text track cue data must be set to the new value.

The user agent will use DataCue to expose only text track cue objects that belong to a text track that has a text track kind of metadata.

DataCue has a constructor to allow script to create DataCue objects in cases where generic metadata needs to be managed for a text track.

The rules for updating the text track rendering for a DataCue simply state that there is no rendering, even when the cues are in showing mode and the text track kind is one of subtitles or captions or descriptions or chapters.

4.7.14.11.7. Text tracks describing chapters

Chapters are segments of a media resource with a given title. Chapters can be nested, in the same way that sections in a document outline can have subsections.

Each text track cue in a text track being used for describing chapters has three key features: the text track cue start time, giving the start time of the chapter, the text track cue end time, giving the end time of the chapter, and the text track rules for extracting the chapter title.

The rules for constructing the chapter tree from a text track are as follows. They produce a potentially nested list of chapters, each of which have a start time, end time, title, and a list of nested chapters. This algorithm discards cues that do not correctly nest within each other, or that are out of order.

  1. Let list be a copy of the list of cues of the text track being processed.
  2. Remove from list any text track cue whose text track cue end time is before its text track cue start time.
  3. Let output be an empty list of chapters, where a chapter is a record consisting of a start time, an end time, a title, and a (potentially empty) list of nested chapters. For the purpose of this algorithm, each chapter also has a parent chapter.
  4. Let current chapter be a stand-in chapter whose start time is negative infinity, whose end time is positive infinity, and whose list of nested chapters is output. (This is just used to make the algorithm easier to describe.)
  5. Loop: If list is empty, jump to the step labeled end.
  6. Let current cue be the first cue in list, and then remove it from list.
  7. If current cue’s text track cue start time is less than the start time of current chapter, then return to the step labeled loop.
  8. While current cue’s text track cue start time is greater than or equal to current chapter’s end time, let current chapter be current chapter’s parent chapter.
  9. If current cue’s text track cue end time is greater than the end time of current chapter, then return to the step labeled loop.
  10. Create a new chapter new chapter, whose start time is current cue’s text track cue start time, whose end time is current cue’s text track cue end time, whose title is current cue’s text track cue data interpreted according to its rules for rendering the cue in isolation, and whose list of nested chapters is empty.

  11. Append new chapter to current chapter’s list of nested chapters, and let current chapter be new chapter’s parent.
  12. Let current chapter be new chapter.
  13. Return to the step labeled loop.
  14. End: Return output.
The following snippet of a WebVTT file shows how nested chapters can be marked up. The file describes three 50-minute chapters, "Astrophysics", "Computational Physics", and "General Relativity". The first has three subchapters, the second has four, and the third has two. [WEBVTT]
WEBVTT
00:00:00.000 --> 00:50:00.000
Astrophysics

00:00:00.000 --> 00:10:00.000
Introduction to Astrophysics

00:10:00.000 --> 00:45:00.000
The Solar System

00:00:00.000 --> 00:10:00.000
Coursework Description

00:50:00.000 --> 01:40:00.000
Computational Physics

00:50:00.000 --> 00:55:00.000
Introduction to Programming

00:55:00.000 --> 01:30:00.000
Data Structures

01:30:00.000 --> 01:35:00.000
Answers to Last Exam

01:35:00.000 --> 01:40:00.000
Coursework Description

01:40:00.000 --> 02:30:00.000
General Relativity

01:40:00.000 --> 02:00:00.000
Tensor Algebra

02:00:00.000 --> 02:30:00.000
The General Relativistic Field Equations
4.7.14.11.8. Event handlers for objects of the text track APIs

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrackList interface:

Event handler Event handler event type
onchange change
onaddtrack addtrack
onremovetrack removetrack

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrack interface:

Event handler Event handler event type
oncuechange cuechange

The following are the event handlers that (and their corresponding event handler event types) must be supported, as event handler IDL attributes, by all objects implementing the TextTrackCue interface:

Event handler Event handler event type
onenter enter
onexit exit
4.7.14.11.9. Best practices for metadata text tracks

This section is non-normative.

Text tracks can be used for storing data relating to the media data, for interactive or augmented views.

For example, a page showing a sports broadcast could include information about the current score. Suppose a robotics competition was being streamed live. The image could be overlayed with the scores, as follows:

In order to make the score display render correctly whenever the user seeks to an arbitrary point in the video, the metadata text track cues need to be as long as is appropriate for the score. For example, in the frame above, there would be maybe one cue that lasts the length of the match that gives the match number, one cue that lasts until the blue alliance’s score changes, and one cue that lasts until the red alliance’s score changes. If the video is just a stream of the live event, the time in the bottom right would presumably be automatically derived from the current video time, rather than based on a cue. However, if the video was just the highlights, then that might be given in cues also.

The following shows what fragments of this could look like in a WebVTT file:

WEBVTT
...

05:10:00.000 --> 05:12:15.000
matchtype:qual
matchnumber:37

...

05:11:02.251 --> 05:11:17.198
red:78

05:11:03.672 --> 05:11:54.198
blue:66

05:11:17.198 --> 05:11:25.912
red:80

05:11:25.912 --> 05:11:26.522
red:83

05:11:26.522 --> 05:11:26.982
red:86

05:11:26.982 --> 05:11:27.499
red:89

...

The key here is to notice that the information is given in cues that span the length of time to which the relevant event applies. If, instead, the scores were given as zero-length (or very brief, nearly zero-length) cues when the score changes, for example saying "red+2" at 05:11:17.198, "red+3" at 05:11:25.912, etc, problems arise: primarily, seeking is much harder to implement, as the script has to walk the entire list of cues to make sure that no notifications have been missed; but also, if the cues are short it’s possible the script will never see that they are active unless it listens to them specifically.

When using cues in this manner, authors are encouraged to use the cuechange event to update the current annotations. (In particular, using the timeupdate event would be less appropriate as it would require doing work even when the cues haven’t changed, and, more importantly, would introduce a higher latency between when the metadata cues become active and when the display is updated, since timeupdate events are rate-limited.)

4.7.14.12. User interface

The controls attribute is a boolean attribute. If present, it indicates that the author has not provided a scripted controller and would like the user agent to provide its own set of controls.

If the attribute is present, or if scripting is disabled for the media element, then the user agent should expose a user interface to the user. This user interface should include features to begin playback, pause playback, seek to an arbitrary position in the content (if the content supports arbitrary seeking), change the volume, change the display of closed captions or embedded sign-language tracks, select different audio tracks or turn on audio descriptions, and show the media content in manners more suitable to the user (e.g., fullscreen video or in an independent resizable window). Other controls may also be made available.

A user agent may provide controls to affect playback of the media resource (e.g., play, pause, seeking, track selection, and volume controls), but such features should not interfere with the page’s normal rendering. For example, such features could be exposed in the media element’s context menu, platform media keys, or a remote control. The user agent may implement this simply by exposing a user interface to the user as described above (as if the controls attribute was present).

If the user agent exposes a user interface to the user by displaying controls over the media element, then the user agent should suppress any user interaction events while the user agent is interacting with this interface. (For example, if the user clicks on a video’s playback control, mousedown events and so forth would not simultaneously be fired at elements on the page.)

Where possible (specifically, for starting, stopping, pausing, and unpausing playback, for seeking, for changing the rate of playback, for fast-forwarding or rewinding, for listing, enabling, and disabling text tracks, and for muting or changing the volume of the audio), user interface features exposed by the user agent must be implemented in terms of the DOM API described above, so that, e.g., all the same events fire.

For the purposes of listing chapters in the media resource, only text tracks in the media element’s list of text tracks that are showing and whose text track kind is chapters should be used. Such tracks must be interpreted according to the rules for constructing the chapter tree from a text track. When seeking in response to a user manipulating a chapter selection interface, user agents should not use the approximate-for-speed flag.

The controls IDL attribute must reflect the content attribute of the same name.


media . volume [ = value ]

Returns the current playback volume, as a number in the range 0.0 to 1.0, where 0.0 is the quietest and 1.0 the loudest.

Can be set, to change the volume.

Throws an IndexSizeError exception if the new value is not in the range 0.0 .. 1.0.

media . muted [ = value ]

Returns true if audio is muted, overriding the volume attribute, and false if the volume attribute is being honored.

Can be set, to change whether the audio is muted or not.

A media element has a playback volume, which is a fraction in the range 0.0 (silent) to 1.0 (loudest). Initially, the volume should be 1.0, but user agents may remember the last set value across sessions, on a per-site basis or otherwise, so the volume may start at other values.

The volume IDL attribute must return the playback volume of any audio portions of the media element. On setting, if the new value is in the range 0.0 to 1.0 inclusive, the media element’s playback volume must be set to the new value. If the new value is outside the range 0.0 to 1.0 inclusive, then, on setting, an IndexSizeError exception must be thrown instead.

A media element can also be muted. If anything is muting the element, then it is muted. (For example, when the direction of playback is backwards, the element is muted.)

The muted IDL attribute must return the value to which it was last set. When a media element is created, if the element has a muted content attribute specified, then the muted IDL attribute should be set to true; otherwise, the user agents may set the value to the user’s preferred value (e.g., remembering the last set value across sessions, on a per-site basis or otherwise). While the muted IDL attribute is set to true, the media element must be muted.

Whenever either of the values that would be returned by the volume and muted IDL attributes change, the user agent must queue a task to fire a simple event named volumechange at the media element.

An element’s effective media volume is determined as follows:

  1. If the user has indicated that the user agent is to override the volume of the element, then the element’s effective media volume is the volume desired by the user. Abort these steps.
  2. If the element’s audio output is muted, the element’s effective media volume is zero. Abort these steps.
  3. Let volume be the playback volume of the audio portions of the media element, in range 0.0 (silent) to 1.0 (loudest).
  4. The element’s effective media volume is volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. The loudest setting may be lower than the system’s loudest possible setting; for example the user could have set a maximum volume.

The muted content attribute on media elements is a boolean attribute that controls the default state of the audio output of the media resource, potentially overriding user preferences.

The defaultMuted IDL attribute must reflect the muted content attribute.

This attribute has no dynamic effect (it only controls the default state of the element).

This video (an advertisement) autoplays, but to avoid annoying users, it does so without sound, and allows the user to turn the sound on.
<video src="adverts.cgi?kind=video" controls autoplay loop muted></video>
4.7.14.13. Time ranges

Objects implementing the TimeRanges interface represent a list of ranges (periods) of time.

interface TimeRanges {
  readonly attribute unsigned long length;
  double start(unsigned long index);
  double end(unsigned long index);
};
media . length

Returns the number of ranges in the object.

time = media . start(index)

Returns the time for the start of the range with the given index.

Throws an IndexSizeError exception if the index is out of range.

time = media . end(index)

Returns the time for the end of the range with the given index.

Throws an IndexSizeError exception if the index is out of range.

The length IDL attribute must return the number of ranges represented by the object.

The start(index) method must return the position of the start of the indexth range represented by the object, in seconds measured from the start of the timeline that the object covers.

The end(index) method must return the position of the end of the indexth range represented by the object, in seconds measured from the start of the timeline that the object covers.

These methods must throw IndexSizeError exceptions if called with an index argument greater than or equal to the number of ranges represented by the object.

When a TimeRanges object is said to be a normalized TimeRanges object, the ranges it represents must obey the following criteria:

  • The start of a range must be greater than the end of all earlier ranges.
  • The start of a range must be less than or equal to the end of that same range.

In other words, the ranges in such an object are ordered, don’t overlap, and don’t touch (adjacent ranges are folded into one bigger range). A range can be empty (referencing just a single moment in time), e.g., to indicate that only one frame is currently buffered in the case that the user agent has discarded the entire media resource except for the current frame, when a media element is paused.

Ranges in a TimeRanges object must be inclusive.

Thus, the end of a range would be equal to the start of a following adjacent (touching but not overlapping) range. Similarly, a range covering a whole timeline anchored at zero would have a start equal to zero and an end equal to the duration of the timeline.

The timelines used by the objects returned by the buffered, seekable and played IDL attributes of media elements must be that element’s media timeline.

4.7.14.14. The TrackEvent interface
[Constructor(DOMString type, optional TrackEventInit eventInitDict)]
interface TrackEvent : Event {
  readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
};

dictionary TrackEventInit : EventInit {
  (VideoTrack or AudioTrack or TextTrack)? track;
};
event . track

Returns the track object (TextTrack, AudioTrack, or VideoTrack) to which the event relates.

The track attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the context information for the event.

4.7.14.15. Event summary

This section is non-normative.

The following events fire on media elements as part of the processing model described above:

Event name Interface Fired when... Preconditions
loadstart Event The user agent begins looking for media data, as part of the resource selection algorithm. networkState equals NETWORK_LOADING
progress Event The user agent is fetching media data. networkState equals NETWORK_LOADING
suspend Event The user agent is intentionally not currently fetching media data. networkState equals NETWORK_IDLE
abort Event The user agent stops fetching the media data before it is completely downloaded, but not due to an error. error is an object with the code MEDIA_ERR_ABORTED. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
error Event An error occurs while fetching the media data or the type of the resource is not supported media format. error is an object with the code MEDIA_ERR_NETWORK or higher. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
emptied Event A media element whose networkState was previously not in the NETWORK_EMPTY state has just switched to that state (either because of a fatal error during load that’s about to be reported, or because the load() method was invoked while the resource selection algorithm was already running). networkState is NETWORK_EMPTY; all the IDL attributes are in their initial states.
stalled Event The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. networkState is NETWORK_LOADING.
loadedmetadata Event The user agent has just determined the duration and dimensions of the media resource and the text tracks are ready. readyState is newly equal to HAVE_METADATA or greater for the first time.
loadeddata Event The user agent can render the media data at the current playback position for the first time. readyState newly increased to HAVE_CURRENT_DATA or greater for the first time.
canplay Event The user agent can resume playback of the media data, but estimates that if playback were to be started now, the media resource could not be rendered at the current playback rate up to its end without having to stop for further buffering of content. readyState newly increased to HAVE_FUTURE_DATA or greater.
canplaythrough Event The user agent estimates that if playback were to be started now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering. readyState is newly equal to HAVE_ENOUGH_DATA.
playing Event Playback is ready to start after having been paused or delayed due to lack of media data. readyState is newly equal to or greater than HAVE_FUTURE_DATA and paused is false, or paused is newly false and readyState is equal to or greater than HAVE_FUTURE_DATA. Even if this event fires, the element might still not be potentially playing, e.g., if the element is paused for user interaction or paused for in-band content.
waiting Event Playback has stopped because the next frame is not available, but the user agent expects that frame to become available in due course. readyState is equal to or less than HAVE_CURRENT_DATA, and paused is false. Either seeking is true, or the current playback position is not contained in any of the ranges in buffered. It is possible for playback to stop for other reasons without paused being false, but those reasons do not fire this event (and when those situations resolve, a separate playing event is not fired either): e.g., the playback ended, or playback stopped due to errors, or the element has paused for user interaction or paused for in-band content.
seeking Event The seeking IDL attribute changed to true, and the user agent has started seeking to a new position.
seeked Event The seeking IDL attribute changed to false after the current playback position was changed.
ended Event Playback has stopped because the end of the media resource was reached. currentTime equals the end of the media resource; ended is true.
durationchange Event The duration attribute has just been updated.
timeupdate Event The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously.
play Event The element is no longer paused. Fired after the play() method has returned, or when the autoplay attribute has caused playback to begin. paused is newly false.
pause Event The element has been paused. Fired after the pause() method has returned. paused is newly true.
ratechange Event Either the defaultPlaybackRate or the playbackRate attribute has just been updated.
resize Event One or both of the videoWidth and videoHeight attributes have just been updated. Media element is a video element; readyState is not HAVE_NOTHING
volumechange Event Either the volume attribute or the muted attribute has changed. Fired after the relevant attribute’s setter has returned.

The following event fires on source element:

Event name Interface Fired when...
error Event An error occurs while fetching the media data or the type of the resource is not supported media format.

The following events fire on AudioTrackList, VideoTrackList, and TextTrackList objects:

Event name Interface Fired when...
change Event One or more tracks in the track list have been enabled or disabled.
addtrack TrackEvent A track has been added to the track list.
removetrack TrackEvent A track has been removed from the track list.

The following event fires on TextTrack objects and track elements:

Event name Interface Fired when...
cuechange Event One or more cues in the track have become active or stopped being active.

The following events fire on track elements:

Event name Interface Fired when...
error Event An error occurs while fetching the track data or the type of the resource is not supported text track format.
load Event A track data has been fetched and successfully processed.

The following events fire on TextTrackCue objects:

Event name Interface Fired when...
enter Event The cue has become active.
exit Event The cue has stopped being active.
4.7.14.16. Security and privacy considerations

The main security and privacy implications of the video and audio elements come from the ability to embed media cross-origin. There are two directions that threats can flow: from hostile content to a victim page, and from a hostile page to victim content.


If a victim page embeds hostile content, the threat is that the content might contain scripted code that attempts to interact with the Document that embeds the content. To avoid this, user agents must ensure that there is no access from the content to the embedding page. In the case of media content that uses DOM concepts, the embedded content must be treated as if it was in its own unrelated top-level browsing context.

For instance, if an SVG animation was embedded in a video element, the user agent would not give it access to the DOM of the outer page. From the perspective of scripts in the SVG resource, the SVG file would appear to be in a lone top-level browsing context with no parent.


If a hostile page embeds victim content, the threat is that the embedding page could obtain information from the content that it would not otherwise have access to. The API does expose some information: the existence of the media, its type, its duration, its size, and the performance characteristics of its host. Such information is already potentially problematic, but in practice the same information can be obtained using the img element, and so it has been deemed acceptable.

However, significantly more sensitive information could be obtained if the user agent further exposes metadata within the content such as subtitles or chapter titles. Such information is therefore only exposed if the video resource passes a CORS resource sharing check. The crossorigin attribute allows authors to control how this check is performed. [FETCH]

Without this restriction, an attacker could trick a user running within a corporate network into visiting a site that attempts to load a video from a previously leaked location on the corporation’s intranet. If such a video included confidential plans for a new product, then being able to read the subtitles would present a serious confidentiality breach.

4.7.14.17. Best practices for authors using media elements

This section is non-normative.

Playing audio and video resources on small devices such as set-top boxes or mobile phones is often constrained by limited hardware resources in the device. For example, a device might only support three simultaneous videos. For this reason, it is a good practice to release resources held by media elements when they are done playing, either by being very careful about removing all references to the element and allowing it to be garbage collected, or, even better, by removing the element’s src attribute and any source element descendants, and invoking the element’s load() method.

Similarly, when the playback rate is not exactly 1.0, hardware, software, or format limitations can cause video frames to be dropped and audio to be choppy or muted.

4.7.14.18. Best practices for implementors of media elements

This section is non-normative.

How accurately various aspects of the media element API are implemented is considered a quality-of-implementation issue.

For example, when implementing the buffered attribute, how precise an implementation reports the ranges that have been buffered depends on how carefully the user agent inspects the data. Since the API reports ranges as times, but the data is obtained in byte streams, a user agent receiving a variable-bit-rate stream might only be able to determine precise times by actually decoding all of the data. User agents aren’t required to do this, however; they can instead return estimates (e.g., based on the average bitrate seen so far) which get revised as more information becomes available.

As a general rule, user agents are urged to be conservative rather than optimistic. For example, it would be bad to report that everything had been buffered when it had not.

Another quality-of-implementation issue would be playing a video backwards when the codec is designed only for forward playback (e.g., there aren’t many key frames, and they are far apart, and the intervening frames only have deltas from the previous frame). User agents could do a poor job, e.g., only showing key frames; however, better implementations would do more work and thus do a better job, e.g., actually decoding parts of the video forwards, storing the complete frames, and then playing the frames backwards.

Similarly, while implementations are allowed to drop buffered data at any time (there is no requirement that a user agent keep all the media data obtained for the lifetime of the media element), it is again a quality of implementation issue: user agents with sufficient resources to keep all the data around are encouraged to do so, as this allows for a better user experience. For example, if the user is watching a live stream, a user agent could allow the user only to view the live video; however, a better user agent would buffer everything and allow the user to seek through the earlier material, pause it, play it forwards and backwards, etc.


When a media element that is paused is removed from a document and not reinserted before the next time the event loop reaches step 1, implementations that are resource constrained are encouraged to take that opportunity to release all hardware resources (like video planes, networking resources, and data buffers) used by the media element. (User agents still have to keep track of the playback position and so forth, though, in case playback is later restarted.)

4.7.15. The map element

Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent.
Tag omission in text/html:
Neither tag is omissible
Content attributes:
Global attributes
name - Name of image map to reference from the usemap attribute
Allowed ARIA role attribute values:
None
Allowed ARIA state and property attributes:
Global aria-* attributes
DOM interface:
interface HTMLMapElement : HTMLElement {
  attribute DOMString name;
  [SameObject] readonly attribute HTMLCollection areas;
  [SameObject] readonly attribute HTMLCollection images;
};

The map element, in conjunction with an img element and any area element descendants, defines an image map. The element represents its children.

The name attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no space characters. The value of the name attribute must not be a compatibility caseless match for the value of the name attribute of another map element in the same document. If the id attribute is also specified, both attributes must have the same value.

map . areas

Returns an HTMLCollection of the area elements in the map.

map . images

Returns an HTMLCollection of the img and object elements that use the map.

The areas attribute must return an HTMLCollection rooted at the map element, whose filter matches only area elements.

The images attribute must return an HTMLCollection rooted at the Document node, whose filter matches only img and object elements that are associated with this map element according to the image map processing model.

The IDL attribute name must reflect the content attribute of the same name.

Image maps can be defined in conjunction with other content on the page, to ease maintenance. This example is of a page with an image map at the top of the page and a corresponding set of text links at the bottom.
<!DOCTYPE HTML>
<TITLE>Babies™: Toys</TITLE>
<HEADER>
  <h1>Toys</h1>
  <IMG SRC="/images/menu.gif"
      ALT="Babies™ navigation menu. Select a department to go to its page."
      USEMAP="#NAV">
</HEADER>
  ...
<FOOTER>
  <MAP NAME="NAV">
  <P>
    <A HREF="/clothes/">Clothes</A>
    <AREA ALT="Clothes" COORDS="0,0,100,50" HREF="/clothes/"> |
    <A HREF="/toys/">Toys</A>
    <AREA ALT="Toys" COORDS="100,0,200,50" HREF="/toys/"> |
    <A HREF="/food/">Food</A>
    <AREA ALT="Food" COORDS="200,0,300,50" HREF="/food/"> |
    <A HREF="/books/">Books</A>
    <AREA ALT="Books" COORDS="300,0,400,50" HREF="/books/">
  </P>
  </MAP>
</FOOTER>

4.7.16. The area element

Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected, but only if there is a map element ancestor or a template element ancestor.
Content model:
Nothing.
Tag omission in text/html:
No end tag
Content attributes:
Global attributes
alt - Replacement text for use when images are not available
coords - Coordinates for the shape to be created in an image map
download - Whether to download the resource instead of navigating to it, and its file name if so
href - Address of the hyperlink
hreflang - Language of the linked resource
rel - Relationship of this document (or subsection/topic) to the destination resource
shape - The kind of shape to be created in an image map
target - browsing context for hyperlink navigation
type - Hint for the type of the referenced resource
Allowed ARIA role attribute values:
link role (default - do not set).
Allowed ARIA state and property attributes:
Global aria-* attributes
Any aria-* attributes applicable to the allowed roles.
DOM interface:
interface HTMLAreaElement : HTMLElement {
  attribute DOMString alt;
  attribute DOMString coords;
  attribute DOMString shape;
  attribute DOMString target;
  attribute DOMString download;
  attribute DOMString rel;
  readonly attribute DOMTokenList relList;
  attribute DOMString hreflang;
  attribute DOMString type;
};
HTMLAreaElement implements HTMLHyperlinkElementUtils;

The area element represents either a hyperlink with some text and a corresponding area on an image map, or a dead area on an image map.

An area element with a parent node must have a map element ancestor or a template element ancestor.

If the area element has an href attribute, then the area element represents a hyperlink. In this case, the alt attribute must be present. It specifies the text of the hyperlink. Its value must be text that informs the user about the destination of the link.

If the area element has no href attribute, then the area represented by the element cannot be selected, and the alt attribute must be omitted.

In both cases, the shape and coords attributes specify the area.

The shape attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The states given in the first cell of the rows with keywords give the states to which those keywords map. Some of the keywords are non-conforming, as noted in the last column.

State Keywords Notes
Circle state circle
circ Non-conforming
Default state default
Polygon state poly
polygon Non-conforming
Rectangle state rect
rectangle Non-conforming

The attribute may be omitted. The missing value default is the rectangle state.

The coords attribute must, if specified, contain a valid list of floating-point numbers. This attribute gives the coordinates for the shape described by the shape attribute. The processing for this attribute is described as part of the image map processing model.

In the circle state, area elements must have a coords attribute present, with three integers, the last of which must be non-negative. The first integer must be the distance in CSS pixels from the left edge of the image to the center of the circle, the second integer must be the distance in CSS pixels from the top edge of the image to the center of the circle, and the third integer must be the radius of the circle, again in CSS pixels.

In the default state state, area elements must not have a coords attribute. (The area is the whole image.)

In the polygon state, area elements must have a coords attribute with at least six integers, and the number of integers must be even. Each pair of integers must represent a coordinate given as the distances from the left and the top of the image in CSS pixels respectively, and all the coordinates together must represent the points of the polygon, in order.

In the rectangle state, area elements must have a coords attribute with exactly four integers, the first of which must be less than the third, and the second of which must be less than the fourth. The four points must represent, respectively, the distance from the left edge of the image to the left side of the rectangle, the distance from the top edge to the top side, the distance from the left edge to the right side, and the distance from the top edge to the bottom side, all in CSS pixels.

When user agents allow users to follow hyperlinks or download hyperlinks created using the area element, as described in the next section, the href, target, and download attributes decide how the link is followed. The rel, hreflang, and type attributes may be used to indicate to the user the likely nature of the target resource before the user follows the link.

The target, download, rel, hreflang, and type attributes must be omitted if the href attribute is not present.

The activation behavior of area elements is to run the following steps:

  1. If the area element’s node document is not fully active, then abort these steps.
  2. If the area element has a download attribute and the algorithm is not allowed to show a popup; or, if the user has not indicated a specific browsing context for following the link, and the element’s target attribute is present, and applying the rules for choosing a browsing context given a browsing context name, using the value of the target attribute as the browsing context name, would result in there not being a chosen browsing context, then run these substeps:

    1. If there is an entry settings object, throw an InvalidAccessError exception.
    2. Abort these steps without following the hyperlink.
  3. Otherwise, the user agent must follow the hyperlink or download the hyperlink created by the area element, if any, and as determined by the download attribute and any expressed user preference.

The IDL attributes alt, coords, target, download, rel, hreflang, and type, each must reflect the respective content attributes of the same name.

The IDL attribute shape must reflect the shape content attribute.

The IDL attribute relList must reflect the rel content attribute.


The area element also supports the HTMLHyperlinkElementUtils interface. [URL]

When the element is created, and whenever the element’s href content attribute is set, changed, or removed, the user agent must invoke the element’s HTMLHyperlinkElementUtils interface’s set the input algorithm with the value of the href content attribute, if any, or the empty string otherwise, as the given value.

The element’s HTMLHyperlinkElementUtils interface’s get the base algorithm must simply return the document base URL.

The element’s HTMLHyperlinkElementUtils interface’s query encoding is the document’s character encoding.

When the element’s HTMLHyperlinkElementUtils interface invokes its update steps with a string value, the user agent must set the element’s href content attribute to the string value.

4.7.17. Image maps

4.7.17.1. Authoring

An image map allows geometric areas on an image to be associated with hyperlinks.

An image, in the form of an img element, may be associated with an image map (in the form of a map element) by specifying a usemap attribute on the img element. The usemap attribute, if specified, must be a valid hash-name reference to a map element.

Consider an image that looks as follows:

A line with four shapes in it, equally spaced: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.

If we wanted just the colored areas to be clickable, we could do it as follows:

<p>
  Please select a shape:
  <img src="shapes.png" usemap="#shapes"
      alt="Four shapes are available: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.">
  <map name="shapes">
  <area shape=rect coords="50,50,100,100"> <!-- the hole in the red box -->
  <area shape=rect coords="25,25,125,125" href="red.html" alt="Red box.">
  <area shape=circle coords="200,75,50" href="green.html" alt="Green circle.">
  <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="Blue triangle.">
  <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465,60"
        href="yellow.html" alt="Yellow star.">
  </map>
</p>
4.7.17.2. Processing model

If an img element has a usemap attribute specified, user agents must process it as follows:

  1. Parse the attribute’s value using the rules for parsing a hash-name reference to a map element, with the element’s node document as the context node. This will return either an element (the map) or null.
  2. If that returned null, then abort these steps. The image is not associated with an image map after all.
  3. Otherwise, the user agent must collect all the area elements that are descendants of the map. Let those be the areas.

Having obtained the list of area elements that form the image map (the areas), interactive user agents must process the list in one of two ways.

If the user agent intends to show the text that the img element represents, then it must use the following steps.

In user agents that do not support images, or that have images disabled, object elements cannot represent images, and thus this section never applies (the fallback content is shown instead). The following steps therefore only apply to img elements.

  1. Remove all the area elements in areas that have no href attribute.
  2. Remove all the area elements in areas that have no alt attribute, or whose alt attribute’s value is the empty string, if there is another area element in areas with the same value in the href attribute and with a non-empty alt attribute.
  3. Each remaining area element in areas represents a hyperlink. Those hyperlinks should all be made available to the user in a manner associated with the text of the img.

    In this context, user agents may represent area and img elements with no specified alt attributes, or whose alt attributes are the empty string or some other non-visible text, in a user-agent-defined fashion intended to indicate the lack of suitable author-provided text.

If the user agent intends to show the image and allow interaction with the image to select hyperlinks, then the image must be associated with a set of layered shapes, taken from the area elements in areas, in reverse tree order (so the last specified area element in the map is the bottom-most shape, and the first element in the map, in tree order, is the top-most shape).

Each area element in areas must be processed as follows to obtain a shape to layer onto the image:

  1. Find the state that the element’s shape attribute represents.
  2. Use the rules for parsing a list of floating-point numbers to parse the element’s coords attribute, if it is present, and let the result be the coords list. If the attribute is absent, let the coords list be the empty list.
  3. If the number of items in the coords list is less than the minimum number given for the area element’s current state, as per the following table, then the shape is empty; abort these steps.

    State Minimum number of items
    Circle state 3
    Default state 0
    Polygon state 6
    Rectangle state 4
  4. Check for excess items in the coords list as per the entry in the following list corresponding to the shape attribute’s state:

    Circle state
    Drop any items in the list beyond the third.
    Default state
    Drop all items in the list.
    Polygon state
    Drop the last item if there’s an odd number of items.
    Rectangle state
    Drop any items in the list beyond the fourth.
  5. If the shape attribute represents the rectangle state, and the first number in the list is numerically greater than the third number in the list, then swap those two numbers around.
  6. If the shape attribute represents the rectangle state, and the second number in the list is numerically greater than the fourth number in the list, then swap those two numbers around.
  7. If the shape attribute represents the circle state, and the third number in the list is less than or equal to zero, then the shape is empty; abort these steps.
  8. Now, the shape represented by the element is the one described for the entry in the list below corresponding to the state of the shape attribute:
    Circle state

    Let x be the first number in coords, y be the second number, and r be the third number.

    The shape is a circle whose center is x CSS pixels from the left edge of the image and y CSS pixels from the top edge of the image, and whose radius is r pixels.

    Default state

    The shape is a rectangle that exactly covers the entire image.

    Polygon state

    Let xi be the (2i)th entry in coords, and yi be the (2i+1)th entry in coords (the first entry in coords being the one with index 0).

    Let the coordinates be (xi, yi), interpreted in CSS pixels measured from the top left of the image, for all integer values of i from 0 to (N/2)-1, where N is the number of items in coords.

    The shape is a polygon whose vertices are given by the coordinates, and whose interior is established using the even-odd rule. [GRAPHICS]

    Rectangle state

    Let x1 be the first number in coords, y1 be the second number, x2 be the third number, and y2 be the fourth number.

    The shape is a rectangle whose top-left corner is given by the coordinate (x1, y1) and whose bottom right corner is given by the coordinate (x2, y2), those coordinates being interpreted as CSS pixels from the top left corner of the image.

    For historical reasons, the coordinates must be interpreted relative to the displayed image after any stretching caused by the CSS width and height properties (or, for non-CSS browsers, the image element’s width and height attributes — CSS browsers map those attributes to the aforementioned CSS properties).

    Browser zoom features and transforms applied using CSS or SVG do not affect the coordinates.

Pointing device interaction with an image associated with a set of layered shapes per the above algorithm must result in the relevant user interaction events being first fired to the top-most shape covering the point that the pointing device indicated, if any, or to the image element itself, if there is no shape covering that point. User agents may also allow individual area elements representing hyperlinks to be selected and activated (e.g., using a keyboard).

Because a map element (and its area elements) can be associated with multiple img and object elements, it is possible for an area element to correspond to multiple focusable areas of the document.

Image maps are live; if the DOM is mutated, then the user agent must act as if it had rerun the algorithms for image maps.

4.7.18. MathML

The math element from the MathML namespace falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

This specification refers to several specific MathML elements, in particular: annotation-xml, merror, mi, mn, mo, ms, and mtext.

When the MathML annotation-xml element contains elements from the HTML namespace, such elements must all be flow content. [MATHML]

When the MathML token elements (mi, mo, mn, ms, and mtext) are descendants of HTML elements, they may contain phrasing content elements from the HTML namespace. [MATHML]

User agents must handle text other than inter-element whitespace found in MathML elements whose content models do not allow straight text by pretending for the purposes of MathML content models, layout, and rendering that the text is actually wrapped in an mtext element in the MathML namespace. (Such text is not, however, conforming.)

User agents must act as if any MathML element whose contents does not match the element’s content model was replaced, for the purposes of MathML layout and rendering, by an merror element in the MathML namespace containing some appropriate error message.

To enable authors to use MathML tools that only accept MathML in its XML form, interactive HTML user agents are encouraged to provide a way to export any MathML fragment as an XML namespace-well-formed XML fragment.

The semantics of MathML elements are defined by the MathML specification and other applicable specifications. [MATHML]

Here is an example of the use of MathML in an HTML document:
<!DOCTYPE html>
<html>
  <head>
  <title>The quadratic formula</title>
  </head>
  <body>
  <h1>The quadratic formula</h1>
  <p>
    <math>
    <mi>x</mi>
    <mo>=</mo>
    <mfrac>
      <mrow>
      <mo form="prefix">-</mo> <mi>b</mi>
      <mo>±</mo>
      <msqrt>
        <msup> <mi>b</mi> <mn>2</mn> </msup>
        <mo>-</mo>
        <mn>4</mn> <mo></mo> <mi>a</mi> <mo></mo> <mi>c</mi>
      </msqrt>
      </mrow>
      <mrow>
      <mn>2</mn> <mo></mo> <mi>a</mi>
      </mrow>
    </mfrac>
    </math>
  </p>
  </body>
</html>

4.7.19. SVG

The svg element from the SVG namespace falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

To enable authors to use SVG tools that only accept SVG in its XML form, interactive HTML user agents are encouraged to provide a way to export any SVG fragment as an XML namespace-well-formed XML fragment.

When the SVG foreignObject element contains elements from the HTML namespace, such elements must all be flow content. [SVG11]

The content model for title elements in the SVG namespace inside HTML documents is phrasing content. (This further constrains the requirements given in the SVG specification.)

The semantics of SVG elements are defined by the SVG specification and other applicable specifications. [SVG11]

User agent requirements: SVG as implemented today follows neither SVG 1.1 nor SVG Tiny 1.2 precisely, instead implementing subsets of each. Although it is hoped that the in-progress SVG 2 specification is a more realistic target for implementations, until that specification is ready, user agents must implement the SVG 1.1 specification with the following willful violations and additions. [SVG11] [SVGTiny12] [SVG2]

The following features from SVG 1.1 must not be implemented:

The following features from SVG Tiny 1.2 must be implemented:

4.7.20. Dimension attributes

Author requirements: The width and height attributes on img, iframe, embed, object, video, and, when their type attribute is in the image button state, input elements may be specified to give the dimensions of the visual content of the element (the width and height respectively, relative to the nominal direction of the output medium), in CSS pixels. The attributes, if specified, must have values that are valid non-negative integers.

The specified dimensions given may differ from the dimensions specified in the resource itself, since the resource may have a resolution that differs from the CSS pixel resolution. (On screens, CSS pixels have a resolution of 96ppi, but in general the CSS pixel resolution depends on the reading distance.) If both attributes are specified, then one of the following statements must be true:

The target ratio is the ratio of the intrinsic width to the intrinsic height in the resource. The specified width and specified height are the values of the width and height attributes respectively.

The two attributes must be omitted if the resource in question does not have both an intrinsic width and an intrinsic height.

If the two attributes are both zero, it indicates that the element is not intended for the user (e.g., it might be a part of a service to count page views).

The dimension attributes are not intended to be used to stretch the image.

User agent requirements: User agents are expected to use these attributes as hints for the rendering.

The width and height IDL attributes on the iframe, embed, object, and video elements must reflect the respective content attributes of the same name.

For iframe, embed, and object the IDL attributes are DOMString; for video the IDL attributes are unsigned long.

The corresponding IDL attributes for img and input elements are defined in those respective elements' sections, as they are slightly more specific to those elements' other behaviors.

4.6 편집Table of contents4.8 Links